Sub topic 13
Testing hooks with renderHook
This chapter assumes you can write a custom hook with useState and useEffect, and that you have used Jest or Vitest with React Testing Library. Here you will test hooks directly, without building a throwaway component for each test.
Why hooks need a test host
A hook can only run inside a component render. If you call useToggle() in a test body, React throws an "Invalid hook call" error. You could write a small component that uses the hook and render it, but that adds code and makes it hard to read the hook's return value.
renderHook from @testing-library/react does this for you. It renders a hidden test component, calls your hook inside it, and gives you the latest return value.
A first test
import { renderHook, act } from '@testing-library/react';
import { useToggle } from './useToggle';
test('useToggle flips its value', () => {
const { result } = renderHook(() => useToggle());
expect(result.current[0]).toBe(false);
act(() => {
result.current[1]();
});
expect(result.current[0]).toBe(true);
});Three details matter here:
renderHooktakes a callback that calls the hook. The callback is the body of the hidden component.result.currentalways holds the value from the most recent render. Read it again after each change. Do not store it in a variable before the change.actwraps anything that causes a state update. It makes React finish the update and re-render before the next line runs. Without it, the test reads stale values and React logs a warning.
What renderHook returns
| Property | Use |
|---|---|
| `result.current` | The hook's latest return value |
| `rerender(newProps)` | Renders again, optionally with new arguments |
| `unmount()` | Unmounts the host, which runs effect cleanups |
Testing arguments that change
Hooks often react to new arguments. Use initialProps to set the first arguments and rerender to change them. This test uses fake timers to check useDebouncedValue.
import { renderHook, act } from '@testing-library/react';
import { useDebouncedValue } from './useDebouncedValue';
test('useDebouncedValue updates after the delay', () => {
jest.useFakeTimers();
const { result, rerender } = renderHook(
({ value, delay }) => useDebouncedValue(value, delay),
{ initialProps: { value: 'a', delay: 200 } }
);
expect(result.current).toBe('a');
rerender({ value: 'b', delay: 200 });
expect(result.current).toBe('a');
act(() => {
jest.advanceTimersByTime(200);
});
expect(result.current).toBe('b');
jest.useRealTimers();
});After rerender, the hook still returns 'a', because the timer has not fired. Advancing the fake clock inside act lets the timer's setDebounced call run. In Vitest, use vi.useFakeTimers() and vi.advanceTimersByTime(200) instead.
Testing cleanup
Cleanup bugs, such as a listener that is never removed, do not show up in the return value. Spy on the browser API and call unmount.
import { renderHook } from '@testing-library/react';
import { useEventListener } from './useEventListener';
test('useEventListener removes its listener on unmount', () => {
const target = document.createElement('div');
const add = jest.spyOn(target, 'addEventListener');
const remove = jest.spyOn(target, 'removeEventListener');
const { unmount } = renderHook(() =>
useEventListener('click', () => {}, target)
);
expect(add).toHaveBeenCalledWith('click', expect.any(Function));
unmount();
expect(remove).toHaveBeenCalledWith('click', expect.any(Function));
});Hooks that need context
If your hook calls useContext, pass a wrapper option. The wrapper is a component that renders its children inside the providers the hook needs.
const { result } = renderHook(() => useTheme(), {
wrapper: ({ children }) => (
<ThemeProvider theme="dark">{children}</ThemeProvider>
),
});Common errors
- Reading
result.currenttoo early. After a state change, read it again. Do not reuse a value you saved earlier. - Missing
act. If you see "not wrapped in act(...)", wrap the call that triggers the update. - Async hooks. For hooks like
useFetchJson, usewaitForfrom Testing Library to wait for thestatusto change. Mockfetchso tests do not hit the network.
Exercise
A test calls const { result } = renderHook(() => useToggle()), then runs const before = result.current[0], calls act(() => result.current[1]()), and asserts expect(before).toBe(true). The assertion fails. Why, and how do you fix it?
Show answer
before holds the value from the first render, which is false. Values saved from result.current do not update. Read result.current[0] again after the act call and assert on that.