Skip to content
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 Walkthrough

Walkthrough Idle
Click "Animate Update" to play the state reconciliation walkthrough.

Reference 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.Automatic batching in React 18+ applies across event handlers, setTimeout, promises, and native event listeners.
  • 02.Batching drastically reduces frame rate drops and duplicate layout calculations.
  • 03.If you ever require synchronous flushing, you can use ReactDOM.flushSync() (use sparingly).

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