ReactMedium

What is batching in React 18?

React 18 introduced automatic batching: state updates are grouped into a single render no matter where they happen, including promises, setTimeout, native event handlers and async functions. Before React 18, only updates inside React event handlers were batched. It applies to apps using createRoot, which is the only root API in React 19.

Before React 18

setTimeout(() => {
  setCount((c) => c + 1); // render
  setFlag((f) => !f);     // render again
}, 0);

React 18+

The same code renders once. This also applies after await in async handlers and in fetch().then() callbacks.

Benefits

  • Fewer renders and better performance with no code changes.
  • Consistent UI: no intermediate states where only some updates were applied.

Opting out

flushSync(() => setX(v)) from react-dom renders synchronously. Use it only when you need the DOM updated immediately, such as measuring or scrolling to a new element.

Migration notes

  • ReactDOM.render kept the old behavior; it was deprecated in 18 and removed in React 19. Use createRoot.
  • Code that read the DOM right after a state update in a timeout may need flushSync.
  • Class setState in timeouts is batched too.

Related React 18 features

Concurrent rendering, useTransition, useDeferredValue, Suspense on the server with streaming, useId, useSyncExternalStore.

Code example

tsx
1import { useState } from "react";
2import { createRoot } from "react-dom/client";
3
4function App() {
5 const [count, setCount] = useState(0);
6 const [loading, setLoading] = useState(false);
7 console.log("render", { count, loading });
8
9 async function load() {
10 setLoading(true);
11 const data: number[] = await fetch("/api/numbers").then((r) => r.json());
12 // React 18+: these two updates produce ONE render, even after await
13 setCount(data.length);
14 setLoading(false);
15 }
16
17 function inTimeout() {
18 setTimeout(() => {
19 setCount((c) => c + 1);
20 setLoading((l) => !l); // batched with the line above
21 }, 0);
22 }
23
24 return (
25 <>
26 <button onClick={load}>{loading ? "Loading…" : `Loaded ${count}`}</button>
27 <button onClick={inTimeout}>Timeout updates</button>
28 </>
29 );
30}
31
32createRoot(document.getElementById("root")!).render(<App />); // automatic batching requires createRoot

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