Sub topic 13
Testing custom hooks with renderHook
This chapter assumes you can already render components, query them, and assert with jest-dom. It also assumes you know what useState, useEffect, and useContext do. The examples use Jest. In Vitest, replace jest.fn() with vi.fn() and import vi from vitest.
Why hooks need a host component
React only runs a hook while a component is rendering. If you call useToggle() directly inside a test, React throws an "Invalid hook call" error, because no component is rendering.
The usual fix has two steps. You write a small throwaway component that calls the hook, then render it. renderHook does this for you. It renders an invisible component, runs your callback inside it, and stores the latest return value in result.current.
renderHook is exported from @testing-library/react since version 13.1. Older tutorials import it from @testing-library/react-hooks. That package is deprecated and does not support React 18, so do not install it.
The basic pattern
Here is a hook that holds a boolean and a function to flip it.
// useToggle.js
import { useCallback, useState } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}The test renders the hook, reads the first value, calls the function, and reads the value again.
// useToggle.test.js
import { renderHook, act } from '@testing-library/react';
import { useToggle } from './useToggle';
test('toggles the value', () => {
const { result } = renderHook(() => useToggle());
expect(result.current[0]).toBe(false);
act(() => {
result.current[1]();
});
expect(result.current[0]).toBe(true);
});Two details matter here.
result.currentis a property that changes over time. Read it again after every update. If you destructure early (const [on, toggle] = result.current),onkeeps its old value forever.- State updates triggered outside React's event system must be wrapped in
act.acttells React to apply the update and re-render before the next line runs. Without it, you read stale values and see "not wrapped in act(...)" warnings.
Passing arguments and re-rendering
A hook's arguments are its props. To test how a hook reacts to new arguments, use initialProps and rerender.
// useCounter.js
import { useCallback, useState } from 'react';
export function useCounter(step = 1) {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount((c) => c + step), [step]);
return { count, increment };
}// useCounter.test.js
import { renderHook, act } from '@testing-library/react';
import { useCounter } from './useCounter';
test('uses the latest step value', () => {
const { result, rerender } = renderHook(({ step }) => useCounter(step), {
initialProps: { step: 1 },
});
act(() => result.current.increment());
expect(result.current.count).toBe(1);
rerender({ step: 5 });
act(() => result.current.increment());
expect(result.current.count).toBe(6);
});rerender re-renders the same hidden component with new props. State survives, because the component is not remounted. This is how you check that a hook responds correctly to changing inputs.
Do not capture a variable in the callback and change it between renders (renderHook(() => useCounter(step)) with a mutable step). It can work, but initialProps makes the inputs explicit and keeps the test readable.
Hooks that need a provider
Hooks that call useContext need the matching provider above them. renderHook accepts the same wrapper option as render.
// useTheme.jsx
import { createContext, useContext } from 'react';
export const ThemeContext = createContext('light');
export function useTheme() {
return useContext(ThemeContext);
}// useTheme.test.jsx
import { renderHook } from '@testing-library/react';
import { ThemeContext, useTheme } from './useTheme';
test('reads the theme from context', () => {
const wrapper = ({ children }) => (
<ThemeContext.Provider value="dark">{children}</ThemeContext.Provider>
);
const { result } = renderHook(() => useTheme(), { wrapper });
expect(result.current).toBe('dark');
});
test('falls back to the default theme without a provider', () => {
const { result } = renderHook(() => useTheme());
expect(result.current).toBe('light');
});If your project already has a custom render helper with several providers, reuse the same provider component as the wrapper. Pass the provider itself, as in { wrapper: AppProviders }, not a rendered element.
Async hooks
A hook that loads data updates its state after a promise settles. Test it the same way you test async UI: wait for the condition you care about with waitFor.
// useUser.js
import { useEffect, useState } from 'react';
export function useUser(loadUser) {
const [state, setState] = useState({ status: 'loading', user: null, error: null });
useEffect(() => {
let cancelled = false;
loadUser()
.then((user) => {
if (!cancelled) setState({ status: 'success', user, error: null });
})
.catch((error) => {
if (!cancelled) setState({ status: 'error', user: null, error });
});
return () => {
cancelled = true;
};
}, [loadUser]);
return state;
}// useUser.test.js
import { renderHook, waitFor } from '@testing-library/react';
import { useUser } from './useUser';
test('loads a user', async () => {
const loadUser = jest.fn().mockResolvedValue({ name: 'Ada' });
const { result } = renderHook(() => useUser(loadUser));
expect(result.current.status).toBe('loading');
await waitFor(() => expect(result.current.status).toBe('success'));
expect(result.current.user).toEqual({ name: 'Ada' });
});
test('reports an error', async () => {
const failure = new Error('Network down');
const loadUser = jest.fn().mockRejectedValue(failure);
const { result } = renderHook(() => useUser(loadUser));
await waitFor(() => expect(result.current.status).toBe('error'));
expect(result.current.error).toBe(failure);
});Notice that loadUser is created once, outside the callback. The hook lists loadUser in its effect dependencies. If you wrote renderHook(() => useUser(jest.fn().mockResolvedValue(...))), a new function would be created on every render, the effect would re-run each time, and the test could loop forever.
waitFor already wraps its polling in act, so you do not add act around it.
Effects and cleanup
renderHook also returns unmount. Use it to confirm that a hook removes what it added.
// useOnEscape.js
import { useEffect } from 'react';
export function useOnEscape(handler) {
useEffect(() => {
function onKeyDown(event) {
if (event.key === 'Escape') handler();
}
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
}, [handler]);
}// useOnEscape.test.js
import { renderHook } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useOnEscape } from './useOnEscape';
test('calls the handler on Escape and stops after unmount', async () => {
const user = userEvent.setup();
const handler = jest.fn();
const { unmount } = renderHook(() => useOnEscape(handler));
await user.keyboard('{Escape}');
expect(handler).toHaveBeenCalledTimes(1);
unmount();
await user.keyboard('{Escape}');
expect(handler).toHaveBeenCalledTimes(1);
});The test drives the hook with a real keyboard event instead of calling an internal function. It then checks the observable effect: the handler is no longer called after unmount.
Choosing between renderHook and a component test
A hook is an implementation detail of the components that use it. Users never see a hook, only the UI it produces. That leads to a simple rule.
| Situation | Better choice |
|---|---|
| The hook is used by one component and has no logic worth reusing | Test the component and skip a separate hook test |
| The hook is shared by many components or published as a library | `renderHook` |
| The hook has many branches that are awkward to reach through the UI | `renderHook` for the branches, plus one component test |
| The hook only wraps another library's hook (for example a data-fetching hook) | Test the component with the network mocked |
Testing a hook through renderHook tests its public contract: arguments in, return value out. Do not assert on its internal state or on how many times it rendered. Those values are not part of the contract, and such tests break when you refactor.
Common errors
- "Invalid hook call": you called the hook outside
renderHook. Move the call inside the callback. - "not wrapped in act(...)": you called a state-changing function from the hook without
act. Wrap the call, or usewaitForor afindByquery for async updates. - Stale values: you destructured
result.currentonce and reused it. Readresult.currentagain after each update. - "Cannot read properties of undefined" from a context hook: the hook needs a provider. Pass a
wrapper. - Infinite re-render or never-settling test: you created a new function or object inside the callback and the hook uses it as a dependency. Create it outside the callback.
Exercise
A hook useDebounce(value, delay) returns the value only after delay milliseconds without changes. How would you write the test setup so it can change value between renders, and which Jest feature would you use to avoid waiting in real time?
Show answer
Render with renderHook(({ value }) => useDebounce(value, 500), { initialProps: { value: 'a' } }), then call rerender({ value: 'b' }) to change the input. Use Jest fake timers (jest.useFakeTimers()) and advance them inside act, for example act(() => { jest.advanceTimersByTime(500); }), then assert that result.current is 'b'. Restore real timers with jest.useRealTimers() after the test.
Exercise
Why does const [on, toggle] = result.current; placed before act(() => toggle()) produce a failing assertion when you later check on?
Show answer
on is a plain boolean copied from the first render. Calling toggle re-renders the hook and puts a new array in result.current, but your on variable still holds the old value. Read result.current[0] again after the act call.