Batching Updates
React groups multiple state updates into a single re-render to optimize performance and prevent unnecessary repaints.
Mental Model
"The Restaurant Waiter: The waiter takes drink, appetizer, and main dish orders together to make one trip to the kitchen."
Interactive Engine Simulation
Executable Code Snippet
1function handleClick() {
2 // In React 18+, these are batched automatically
3 // even inside promises or timeouts!
4 setCount(c => c + 1);
5 setFlag(f => !f);
6 // Only ONE re-render occurs here
7}- 01.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
01. Grouping for Performance
Automatic batching is a performance feature where React groups multiple state updates into a single re-render. Before React 18, only updates inside event handlers were batched. Now, updates inside Promises, `setTimeout`, or native event listeners are also batched.
Batching logic
02. flushSync (The Escape)
In rare cases, you might need to force a synchronous update (e.g., to measure the DOM immediately after a change). You can use `flushSync` to opt out of batching, though it's generally discouraged as it hurts performance.
Architectural Advice
"Batching is why you can't rely on state being updated immediately after calling the setter. If you need to perform an action based on multiple updates, batching ensures the intermediate 'broken' states are never visible to the user."