javascript / intermediate
Snippet
Testing Custom Hook State Transitions with renderHook
Testing custom React hooks in isolation requires renderHook from React Testing Library. Any state updates triggered inside the test must be wrapped in act() to ensure React flushes all scheduled effects and state transitions synchronously.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { renderHook, act } from '@testing-library/react';import { useState, useCallback } from 'react';function useCounter(initialValue = 0) {const [count, setCount] = useState(initialValue);const increment = useCallback(() => setCount((prev) => prev + 1), []);return { count, increment };}describe('useCounter', () => {it('increments count correctly on action', () => {const { result } = renderHook(() => useCounter(5));expect(result.current.count).toBe(5);act(() => {result.current.increment();});expect(result.current.count).toBe(6);});});
react
Breakdown
1
import { renderHook, act } from '@testing-library/react';
Imports utilities for testing hook lifecycles and wrapping state dispatchers.
2
const { result } = renderHook(() => useCounter(5));
Mounts the hook into an isolated test harness and exposes its return values in the result object.
3
act(() => { result.current.increment(); });
Executes the state modifying function within React's act boundary to apply updates immediately.
4
expect(result.current.count).toBe(6);
Asserts that the hook state reflects the updated primitive value.