Skip to content

Commit

Permalink
fix: useUpdateEffect returns optional cleanup function
Browse files Browse the repository at this point in the history
  • Loading branch information
adesurirey committed Jan 7, 2020
1 parent 662403f commit 0ce421c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
4 changes: 3 additions & 1 deletion src/useUpdateEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ const useUpdateEffect: typeof useEffect = (effect, deps) => {
const isFirstMount = useFirstMountState();

useEffect(() => {
!isFirstMount && effect();
if (!isFirstMount) {
return effect();
}
}, deps);
};

Expand Down
21 changes: 15 additions & 6 deletions tests/useUpdateEffect.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
import { renderHook } from '@testing-library/react-hooks';
import { useUpdateEffect } from '../src';

const mockEffectCleanup = jest.fn();
const mockEffectCallback = jest.fn().mockReturnValue(mockEffectCleanup);

it('should run effect on update', () => {
const { rerender } = renderHook(() => useUpdateEffect(mockEffectCallback));
expect(mockEffectCallback).not.toHaveBeenCalled();
const effect = jest.fn();

const { rerender } = renderHook(() => useUpdateEffect(effect));
expect(effect).not.toHaveBeenCalled();

rerender();
expect(mockEffectCallback).toHaveBeenCalledTimes(1);
expect(effect).toHaveBeenCalledTimes(1);
});

it('should run cleanup on unmount', () => {
const cleanup = jest.fn();
const hook = renderHook(() => useUpdateEffect(cleanup));

hook.rerender();
hook.unmount();

expect(cleanup).toHaveBeenCalledTimes(1);
});

0 comments on commit 0ce421c

Please sign in to comment.