0
Challenge · 86Tooling & Quality

Hook Testing

Testingused in ~35% of apps

Your useToggle, useDebounce, and useLocalStorage carry the trickiest logic in the app — but a hook can't be rendered on its own, and clicking through ten components that use it is no way to prove it works. renderHook lets you test a hook in isolation, the way you'd test a pure function.

Core idea. renderHook mounts a hook inside a throwaway component and hands you a live result.current reference; you drive state by calling the hook's functions inside act(...), then assert on result.current — testing the LOGIC directly, not any UI that consumes it.
Playground, this isn't a screenshot
useCounter.js — the hook under test
function useCounter(start = 0) {
  const [count, setCount] = useState(start);
  const increment = () => setCount((c) => c + 1);  return { count, increment };
}
useCounter.test.js — renderHook
// render the hook in isolation — no component needed
const { result } = renderHook(() => useCounter());
result.current={ count: 0, increment }
// state updates must run inside act()
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(0);PASS
called act() 0× · count 0

Each press wraps the state update in act(), so React flushes it before you assert. Read the new state off result.current and check it with expect(...).toBe() — the test stays green.

↑ play a little first, then dig in