Skip to content

Commit

Permalink
fix: useController() hook triggers rerenders if it is used without de…
Browse files Browse the repository at this point in the history
…pendencies.
  • Loading branch information
mnasyrov committed Sep 14, 2021
1 parent a77e359 commit f0b5582
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
19 changes: 19 additions & 0 deletions packages/rx-effects-react/src/useController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,25 @@ describe('useController()', () => {
expect(destroy).toBeCalledTimes(1);
});

it('should not recreate the controller with empty dependencies after rerendering', () => {
const destroy = jest.fn();

const createController = () => ({ destroy });

const { result, rerender, unmount } = renderHook(() =>
useController(createController),
);

const controller1 = result.current;
rerender();
const controller2 = result.current;

expect(controller1 === controller2).toBe(true);

unmount();
expect(destroy).toBeCalledTimes(1);
});

it('should recreate the controller if a dependency is changed', () => {
const destroy = jest.fn();

Expand Down
4 changes: 3 additions & 1 deletion packages/rx-effects-react/src/useController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import { useEffect, useMemo } from 'react';
import { Controller } from 'rx-effects';

const EMPTY_DEPENDENCIES: unknown[] = [];

/**
* Creates an ad-hoc controller by the factory and destroys it on unmounting a
* component.
Expand All @@ -16,7 +18,7 @@ import { Controller } from 'rx-effects';
*/
export function useController<T extends Controller<Record<string, any>>>(
factory: () => T,
dependencies?: unknown[],
dependencies: unknown[] = EMPTY_DEPENDENCIES,
): T {
const controller = useMemo(factory, dependencies);
useEffect(() => controller.destroy, [controller]);
Expand Down

0 comments on commit f0b5582

Please sign in to comment.