← All tasksReact · Middle
usePrevious hook
Write a usePrevious(value) hook that returns the value from the previous render. On the first render there's no previous value yet - return undefined.
This hook helps compare a prop with its old value, for example to animate a changing number.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (3)
const { result } = renderHook(({ v }) => usePrevious(v), { initialProps: { v: 1 } }); expect(result.current).toBe(undefined);
const { result, rerender } = renderHook(({ v }) => usePrevious(v), { initialProps: { v: 1 } }); rerender({ v: 2 }); expect(result.current).toBe(1);
const { result, rerender } = renderHook(({ v }) => usePrevious(v), { initialProps: { v: 'a' } }); rerender({ v: 'b' }); rerender({ v: 'c' }); expect(result.current).toBe('b');