Skip to main content

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:

javascript
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:

javascript
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:

javascript
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:

javascript
setState() → (React queues it) setState() → (React queues it) --- batch complete --- → one render and commit

Comparison example

Without batching (React 17)

javascript
setCount(c => c + 1); // render #1 setFlag(f => !f); // render #2

Two separate re-renders → more overhead and UI flickering.


With batching (React 18)

javascript
setCount(c => c + 1); setFlag(f => !f); // React combines them → one render

One 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:

javascript
import { flushSync } from "react-dom"; flushSync(() => { setCount(c => c + 1); }); // React will perform the update immediately (without batching)

Key advantages of Automatic Batching

AdvantageDescription
Fewer re-rendersUpdates are grouped → less overhead on the virtual and real DOM
A smoother interfaceReact is not blocked by many small updates
Less code for optimizationYou do not need to manually "combine" setState calls
Works everywhereEven 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.