ReactMedium
What is batching?
Batching means React groups multiple state updates into a single re-render instead of rendering after each one. Since React 18, batching is automatic everywhere: in event handlers, promises, setTimeout, native event listeners and any other context.
Before and after React 18
- React 17 and earlier: only updates inside React event handlers were batched. Updates in
setTimeout, promises or native listeners each caused a separate render. - React 18+ with
createRoot: all updates are batched automatically (the legacyReactDOM.renderroot kept old behavior and was removed in React 19).
Why it matters
- Fewer renders, better performance.
- No intermediate "half-updated" UI where one state value changed but another has not yet.
Consequences
- Reading state right after setting it shows the old value; the new value appears in the next render.
- Several setters in one handler produce one render.
- Updater functions (
setX((prev) => ...)) are queued and applied in order during that render.
Opting out
flushSync(() => setX(value)) from react-dom forces a synchronous render and DOM update. Use it only when you must read the updated DOM immediately (for example to scroll to a newly added element) because it hurts performance.
Related
Transitions are batched separately from urgent updates and can be interrupted.
Code example
tsx
1import { useState } from "react";2import { flushSync } from "react-dom";34export function BatchDemo() {5 const [count, setCount] = useState(0);6 const [flag, setFlag] = useState(false);7 console.log("render", { count, flag });89 async function handleClick() {10 // One render for both updates (event handler)11 setCount((c) => c + 1);12 setFlag((f) => !f);1314 await new Promise((r) => setTimeout(r, 100));1516 // Still one render for both updates (React 18+ batches after await too)17 setCount((c) => c + 1);18 setFlag((f) => !f);19 }2021 function forceSync() {22 flushSync(() => setCount((c) => c + 1)); // DOM updated immediately here23 console.log(document.getElementById("count")?.textContent);24 }2526 return (27 <div>28 <p id="count">{count}</p>29 <button onClick={handleClick}>Batched updates</button>30 <button onClick={forceSync}>flushSync</button>31 </div>32 );33}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.