Testing State Updates with act and waitFor
You'll learn when to use act for synchronous state changes and waitFor for asynchronous operations inside hook tests.
When testing custom hooks, React needs to know when state updates are happening so it can properly batch and flush them. Without this coordination, you'll see cryptic warnings about "not wrapped in act(...)" or tests that read stale values.
The Core Problem
Imagine React's state update queue as a postal service. Synchronous updates are like letters dropped directly in a mailbox—they get processed immediately. Asynchronous updates are like packages requiring signatures—they arrive later. Your test needs to wait at the right times to check the "mail."
When to Use act
For synchronous state updates triggered by hooks (like updating state directly in your test), wrap them in act:
import { renderHook, act } from '@testing-library/react';
test('toggles a boolean state', () => {
const { result } = renderHook(() => useToggle(false));
act(() => {
result.current.toggle(); // synchronous state update
});
expect(result.current.value).toBe(true);
});
When to Use waitFor
For asynchronous operations (timers, promises, API calls inside hooks), use waitFor:
test('fetches data after delay', async () => {
const { result } = renderHook(() => useDebouncedFetch());
act(() => {
result.current.trigger();
});
await waitFor(() => {
expect(result.current.data).toBeDefined();
});
});
waitFor polls your assertion repeatedly until it passes or times out—perfect for state changes you can't predict the exact timing of.
Key Takeaway: Use act to wrap synchronous state updates in hook tests; use waitFor with async/await for asynchronous operations that update state unpredictably.