All topics
Advancedintermediate

The act() Testing Utility and Why It Matters

Understand what act() does under the hood and why React testing utilities require wrapping state updates in it.

act() is a testing utility that ensures all state updates, effects, and their resulting re-renders triggered within its callback are fully processed and flushed before your test proceeds to make assertions — mirroring how React batches and processes updates in a real browser environment inside event handlers. Testing Library's own utilities (render, fireEvent, userEvent) already wrap their internal operations in act() for you, which is why most everyday component tests don't need to call it explicitly.

act() is like insisting a chef fully plate and finish a dish (flush all pending updates and re-renders) before letting a food critic (your test assertion) taste and review it, rather than letting the critic take a bite mid-preparation and unfairly judge an unfinished plate.

Key Concepts

1
Without act(), a test could assert on the DOM immediately after triggering a state update, but before React has actually finished re-rendering and committing that update — since some of React's internal scheduling happens asynchronously (via microtasks or the scheduler), a raw, un-wrapped update might not be reflected in the DOM at the exact moment your very next line of test code runs, leading to flaky, timing-dependent test failures.
act()
2
You'll typically encounter needing act() explicitly when testing custom hooks with renderHook (calling a returned setter function needs wrapping in act()) or in rarer cases where you're manually triggering an update outside of Testing Library's own already-wrapped helper functions — seeing the 'not wrapped in act()' warning in test output is React's way of flagging that a state update happened without a guarantee it was fully flushed before your next assertion.
act()renderHook
3
Interviewers ask candidates to explain what the 'not wrapped in act()' console warning actually means and how to fix it, expecting an answer that connects it to ensuring updates are fully flushed and committed before assertions run, rather than treating it as an arbitrary warning to silence without understanding its purpose.