fix: useUpdateEffect returns optional cleanup function

This commit is contained in:
Arnaud de Surirey 2020-01-07 19:08:38 +01:00
parent 662403f5c3
commit 0ce421ced7
No known key found for this signature in database
GPG Key ID: 1C7438F9FEF9D061
2 changed files with 18 additions and 7 deletions

View File

@ -5,7 +5,9 @@ const useUpdateEffect: typeof useEffect = (effect, deps) => {
const isFirstMount = useFirstMountState();
useEffect(() => {
!isFirstMount && effect();
if (!isFirstMount) {
return effect();
}
}, deps);
};

View File

@ -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);
});