Testing React Hooks
Test custom hooks in isolation with renderHook and act to handle state updates.
What you'll learn
- Why hooks need a host component to be tested
- Using renderHook from @testing-library/react
- Wrapping state updates in act to flush effects
- Testing effects, reducers, and async hooks
Concept
Hooks Need a Host
A custom hook is just a function that uses React primitives, but the Rules of Hooks require it to run inside a React component. You cannot call useMyHook() directly in a test. renderHook from @testing-library/react provides a hidden host component, runs your hook inside it, and gives you a result.current ref that always points at the latest hook return value.
renderHook
Call const { result, rerender, unmount } = renderHook(() => useMyHook(props)). Read the current return with result.current. Call rerender with new props to test prop-driven changes, and unmount to test cleanup effects. For hooks that expose callbacks that update state, invoke the callback and then read result.current again — React batches updates, so the ref reflects the post-update value.
The act Warning
React insists that anything which might cause a state update — a callback, an effect, a resolved promise — happens inside act. Testing Library wraps renderHook and userEvent in act automatically, but when you manually await a promise or trigger a timer, you may need await act(async () => { ... }). Ignoring act warnings leads to tests that pass but do not reflect real React behavior.
Effects and Async
Effects that fetch data or subscribe to a store are the trickiest. Use waitFor to wait for result.current to reach the expected state after the async work settles. Test cleanup by unmounting and asserting that subscriptions were torn down (often via a spy on the unsubscribe function). Fake timers help when effects debounce or poll.
In Practice
When testing a data-fetching hook, mock the fetch with MSW or a stubbed API client, render the hook, and use waitFor to assert that result.current.data eventually equals the expected value and result.current.isLoading becomes false. Test the error path by making the mock reject and asserting the hook surfaces the error. For hooks with cleanup (subscriptions, intervals), call unmount() and verify the teardown ran — a spy on the unsubscribe function makes this concrete. Keep each hook test focused on one piece of behavior (loading state, success, error, cleanup) rather than cramming all paths into one test. If a hook is complex enough that testing it is painful, consider extracting pure logic into a plain function you can unit-test directly, leaving the hook as a thin wrapper.
Example
import { describe, it, expect } from "vitest";
import { renderHook, act } from "@testing-library/react";
import { useCounter } from "./useCounter";
describe("useCounter", () => {
it("increments and decrements", () => {
const { result } = renderHook(() => useCounter(0));
act(() => result.current.increment());
expect(result.current.count).toBe(1);
act(() => result.current.decrement());
expect(result.current.count).toBe(0);
});
it("respects an initial value", () => {
const { result } = renderHook(() => useCounter(10));
expect(result.current.count).toBe(10);
});
});
renderHook hosts the hook in a hidden component. act wraps each state update so React flushes it before the assertion reads result.current.
Try it
- JSON Formatter
Inspect the values your hook returns across renders.
- Code Diff
Compare hook return shapes when refactoring internals.
Common mistakes
The mistake
Reading result.current without wrapping updates in act
The fix
Wrap any callback that triggers a state update in act(() => ...). Without act, React warns and the assertion may read a stale value.
The mistake
Calling a hook directly in a test function
The fix
Hooks must run inside a component. Always use renderHook (or render a small test component) — never call useXxx() in a bare test.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.