Back to Pathway
internalsadvanced

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

Simulation Engine Idle
Click "Execute Code" to run state reconciliation simulation.

Executable Code Snippet

Component.jsx
JSX / React 19
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}
Technical Takeaways & Best Practices
  • 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

Update A
Update B
Update C
↓ (Batch) ↓
Single Render

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."