Testing React components · mid
Testing custom hooks
Test most hooks through a component that uses them, and test a reusable hook directly with renderHook from @testing-library/react, reading result.current, updating inside act, rerendering with new props, and wrapping it in the providers it needs.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- renderHook(() => useCounter(5)) returns { result, rerender, unmount }; result.current is the latest return value.
- State updates triggered from the test go inside act(() => result.current.increment()); async results: await waitFor(() => expect(result.current.data).toEqual(...)).
- Providers: renderHook(() => useCart(), { wrapper: ({ children }) => <CartProvider>{children}</CartProvider> }). Data hooks need a fresh QueryClient per test.
- rerender({ id: 2 }) with initialProps to test dependency changes; unmount() to test cleanup (subscriptions removed, requests aborted).
- @testing-library/react-hooks is deprecated; renderHook lives in @testing-library/react (and RNTL for React Native; in RNTL 14 it is async).
- Don't save result.current in a variable and read it after an update: it will be the old value.
The red pen
Common traps: mistake → fix
Mistake: "const { count } = result.current; act(increment); expect(count).toBe(6)"
Fix: count is a stale snapshot; read result.current again.
Mistake: "Every hook needs its own renderHook tests"
Fix: app-specific hooks are usually better tested through the component's behaviour.
Mistake: "Share one QueryClient across tests"
Fix: cached data leaks between tests; create one per test with retries off.
Easy to hard
Questions interviewers ask, easy to hard
- How do you test a custom hook?
- When would you test a hook directly instead of through a component?
- How do you test a hook that uses context or React Query?
- How do you test that a hook cleans up its subscription on unmount?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.