Skip to content
react questions

React · 10 of 13middle~1 min

How does React handle batching of state updates?

#core#performance#hooks

State update batching

Batching is the merging of multiple setState calls into a single re-render for optimization.

Before React 18

Batching only worked inside React event handlers. Inside setTimeout, Promise, or native events - each setState triggered a separate re-render.

tsx
// React 17 - 2 re-renders (inside setTimeout) setTimeout(() => { setCount(c => c + 1); // re-render setFlag(f => !f); // re-render }, 1000);

React 18 - Automatic Batching

Now batching works everywhere automatically.

tsx
// React 18 - 1 re-render (even inside setTimeout) setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); // one re-render }, 1000);

How to opt out of batching

tsx
import { flushSync } from 'react-dom'; flushSync(() => setCount(c => c + 1)); // immediate re-render flushSync(() => setFlag(f => !f)); // second immediate re-render

flushSync is rarely used - for example when integrating with animation libraries or when you need to synchronously read the DOM after an update.

updated

did you know it?

read more on the blog

view all

related questions