javascript / intermediate
Snippet
Automatic Batching in React 18
Before React 18, state updates were only batched inside React event handlers. Now, updates inside promises, timeouts, or native event handlers are also batched automatically, significantly reducing the number of re-renders and improving performance.
snippet.js
1
2
3
4
5
setTimeout(() => {setCount(c => c + 1);setFlag(f => !f);// In React 18, this results in only one re-render}, 1000);
react
Breakdown
1
setTimeout(() => {
An asynchronous timeout function where batching used to fail in older versions.
2
setCount(c => c + 1);
First state update queued for the next render cycle.
3
setFlag(f => !f);
Second state update queued; React 18 combines this with the previous call into a single render.