What is batching (Automatic Batching)?
What batching is
Batching is a mechanism where React groups several state updates (setState / useState) into a single render, to reduce the number of re-renders and improve performance.
Before React 18 (legacy batching)
Previously (before React 18) React could only group (batch) updates inside synchronous React event handlers.
For example:
function handleClick() {
setCount(c => c + 1);
setFlag(f => !f);
}React performs a single render, because both setState calls are inside one React event (onClick).
But here is what happened in async contexts:
setTimeout(() => {
setCount(c => c + 1);
setFlag(f => !f);
}, 1000);React 17 and below performed two separate renders, because batching did not work outside React events.
React 18: Automatic Batching
In React 18, batching became automatic in every context -
even inside setTimeout, promises, async/await, fetch, effects, and so on.
The same code now works more efficiently:
setTimeout(() => {
setCount(c => c + 1);
setFlag(f => !f);
}, 1000);React 18 performs only one render, since both updates are automatically combined into one batch.
What happens under the hood
When setState() (or a useState update) is called:
- React does not update the DOM immediately;
- it collects all the changes that happen "within one cycle";
- then it performs a single shared render and updates the DOM all at once.
In other words:
setState() → (React queues it)
setState() → (React queues it)
--- batch complete ---
→ one render and commitComparison example
Without batching (React 17)
setCount(c => c + 1); // render #1
setFlag(f => !f); // render #2Two separate re-renders → more overhead and UI flickering.
With batching (React 18)
setCount(c => c + 1);
setFlag(f => !f);
// React combines them → one renderOne render → faster and smoother.
When batching does not happen
Sometimes you need to update the DOM immediately, bypassing batching - for example, to instantly see an effect before the next updates. There is an API for this:
import { flushSync } from "react-dom";
flushSync(() => {
setCount(c => c + 1);
});
// React will perform the update immediately (without batching)Key advantages of Automatic Batching
| Advantage | Description |
|---|---|
| Fewer re-renders | Updates are grouped → less overhead on the virtual and real DOM |
| A smoother interface | React is not blocked by many small updates |
| Less code for optimization | You do not need to manually "combine" setState calls |
| Works everywhere | Even in setTimeout, promises, async functions, fetch, and so on |
Summary
Automatic Batching is the automatic combining of several
setState()calls into one render, regardless of context, to improve performance and the smoothness of the interface.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.