act – React
act – React
v19
act
act is a test helper to apply pending React updates before making
assertions.
Note
You might find using act() directly a bit too verbose. To avoid some
of the boilerplate, you could use a library like React Testing Library,
whose helpers are wrapped with act() .
Reference
Usage
Troubleshooting
Reference
When writing UI tests, tasks like rendering, user events, or data fetching can
be considered as “units” of interaction with a user interface. React provides a
helper called act() that makes sure all updates related to these “units” have
been processed and applied to the DOM before you make any assertions.
Note
Parameters
https://react.dev/reference/react/act 2/7
20/02/2025, 09:07 act – React
process and apply any changes to the DOM. Since it is async, React will
also run any code that crosses an async boundary, and flush any updates
scheduled.
Returns
Usage
When testing a component, you can use act to make assertions about its
output.
For example, let’s say we have this Counter component, the usage examples
below show how to test it:
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(prev => prev + 1);
}
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</div>
)
}
https://react.dev/reference/react/act 3/7
20/02/2025, 09:07 act – React
To test the render output of a component, wrap the render inside act() :
Using act ensures that all updates have been applied before we make
assertions.
https://react.dev/reference/react/act 4/7
20/02/2025, 09:07 act – React
document.body.appendChild(container);
Here, we render the component with act , and then dispatch the event inside
another act() . This ensures that all updates from the event are applied
before making assertions.
Pitfall
Don’t forget that dispatching DOM events only works when the DOM
container is added to the document. You can use a library like React
Testing Library to reduce the boilerplate code.
Troubleshooting
https://react.dev/reference/react/act 5/7
20/02/2025, 09:07 act – React
environment.
If you don’t set the global, you will see an error like this:
Console
To fix, add this to your global setup file for React tests:
global.IS_REACT_ACT_ENVIRONMENT=true
Note
PREVIOUS
APIs
NEXT
cache
https://react.dev/reference/react/act 6/7
20/02/2025, 09:07 act – React
uwu?
Describing the UI
Adding Interactivity
Managing State
Escape Hatches
Community More
Acknowledgements Terms
https://react.dev/reference/react/act 7/7