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 legacy ReactDOM.render root 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";
3
4export function BatchDemo() {
5 const [count, setCount] = useState(0);
6 const [flag, setFlag] = useState(false);
7 console.log("render", { count, flag });
8
9 async function handleClick() {
10 // One render for both updates (event handler)
11 setCount((c) => c + 1);
12 setFlag((f) => !f);
13
14 await new Promise((r) => setTimeout(r, 100));
15
16 // Still one render for both updates (React 18+ batches after await too)
17 setCount((c) => c + 1);
18 setFlag((f) => !f);
19 }
20
21 function forceSync() {
22 flushSync(() => setCount((c) => c + 1)); // DOM updated immediately here
23 console.log(document.getElementById("count")?.textContent);
24 }
25
26 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.

Open in study app