Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 17.6 — Testing Hooks, Context and Reducers
React · Example 1 of 3

renderHook: result.current, act and rerender

The last test fails on purpose: count was copied out of the first render's result, so it stays 0. Read result.current.count after the update instead. Note that initial changing on rerender doesn't reset the count: useState only uses its initial value once.

Test custom hooks with renderHook and act, give components and hooks the providers they need through a wrapper (usually inside a custom render helper), and test reducers as plain functions with no React at all.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a renderHook test (live helper style) for useToggle(initial) returning [on, toggle]: it starts at the initial value and flips on toggle.

02

Write a custom renderWithTheme(ui, { theme }) helper for a ThemeContext, and a test that a ThemedButton shows class dark in dark mode.

Explain it without notes

01

When do you test a custom hook with renderHook and when through a component?

02

Why must you read result.current after each update, and why wrap hook calls in act?

03

How do you test components that need context, a router or a store?

04

Why are reducers easy to test, and what should reducer tests cover?

renderHook: result.current, act and rerender

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

✓ starts at the initial value
✓ increment and decrement update the count
✓ never goes above max
✓ rerender passes new props to the hook
✗ stale result: reading a saved copy instead of result.current: expected 1, got 0