Sub topic 7
How React Batches Multiple Updates
This chapter assumes you can write a function component that calls useState, that you know why a handler sees a snapshot of state, and that you have seen updater functions such as setCount(c => c + 1). Here you will see how React groups several state updates into one render, when that grouping happens, and how to observe it.
What batching means
Batching is React's practice of collecting every state update made during one piece of work and then rendering once. Calling a setter does not render the component. It adds an update to a queue and asks React to render later. After your event handler returns, React processes the whole queue and re-renders once.
Consider this component:
import { useState } from 'react';
function Pair() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
console.log('render', a, b);
function handleClick() {
setA(a + 1);
setB(b + 1);
console.log('in handler', a, b);
}
return <button onClick={handleClick}>a={a}, b={b}</button>;
}On the first click, the console prints in handler 0 0 and then render 1 1. You will never see render 1 0. The handler sees the old snapshot, and React renders once with both updates applied. In development, Strict Mode renders each component twice on purpose, so you may see each render line twice. That does not mean batching failed.
Batching has two benefits:
- Performance. One render replaces several, so React does less work.
- Consistency. The screen never shows a half-updated state, such as a new
apaired with an oldb.
The sequence of events
The diagram shows what happens during one click.
How the queue is processed
When React renders, it starts from the previous state and applies each queued update in order. Each update is one of two kinds:
- A value, such as
setCount(5). It replaces the pending state. - An updater function, such as
setCount(c => c + 1). It receives the pending state and returns the next one.
Here is a queue that mixes both kinds:
import { useState } from 'react';
function Queue() {
const [number, setNumber] = useState(0);
function handleClick() {
setNumber(number + 5); // replace with 0 + 5
setNumber(n => n + 1); // updater: 5 + 1
setNumber(42); // replace with 42
}
return <button onClick={handleClick}>{number}</button>;
}React walks the queue like this:
| Queued update | Pending state before | Pending state after |
|---|---|---|
| `number + 5` (evaluates to 5) | 0 | 5 |
| `n => n + 1` | 5 | 6 |
| `42` | 6 | 42 |
The next render shows 42. This explains a common surprise. Calling the same setter several times with a value computed from the snapshot, such as setCount(count + 1) three times, queues three updates that all say "replace with 1". The last one wins, and the count rises by one. Updater functions chain through the queue, which is why setCount(c => c + 1) three times adds three.
Different setters, one render
The batching rule does not depend on which state variable you update. Updates to separate useState variables in the same handler still produce one render. Separate variables are therefore not a performance problem in themselves. You can split state into several useState calls, or combine it into one object, without paying for extra renders.
Automatic batching in React 18
React 18 changed when batching applies. The behavior below assumes you render with createRoot.
- React 17 and earlier. React batched updates only inside React event handlers. Updates inside a
setTimeout, a promise callback, or a native event listener each caused their own render. - React 18 with
createRoot. React batches updates wherever they come from. This is called automatic batching.
This handler batches in React 18 even though the updates happen later and outside React's event system:
import { useState } from 'react';
function Delayed() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
console.log('render', a, b);
function handleClick() {
setTimeout(() => {
setA(x => x + 1);
setB(y => y + 1);
}, 500);
}
return <button onClick={handleClick}>a={a}, b={b}</button>;
}After half a second, the console shows a single render 1 1. If an app still uses the legacy ReactDOM.render, it keeps the React 17 behavior.
Updates after an await
Batching works on one synchronous stretch of code. An await splits a function into separate stretches, and each stretch is batched on its own:
import { useState } from 'react';
function Save() {
const [status, setStatus] = useState('idle');
const [saved, setSaved] = useState(false);
async function handleClick() {
setStatus('saving'); // batched with the next line
setSaved(false);
await new Promise(resolve => setTimeout(resolve, 300));
setStatus('done'); // a new batch
setSaved(true);
}
return (
<button onClick={handleClick}>
{status} {saved ? '(saved)' : ''}
</button>
);
}This code renders twice: once for the first pair of updates and once for the second pair. Each pair is consistent, so there is no half-updated screen in either case.
Opting out with flushSync
Rarely, you need the DOM to reflect a state change before the next line runs. flushSync from react-dom forces React to render the updates inside its callback immediately:
import { useState } from 'react';
import { flushSync } from 'react-dom';
function Flush() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
console.log('render', a, b);
function handleClick() {
flushSync(() => {
setA(x => x + 1);
});
// The DOM already shows the new a here.
flushSync(() => {
setB(y => y + 1);
});
}
return <button onClick={handleClick}>a={a}, b={b}</button>;
}The click now logs two renders, render 1 0 and then render 1 1. A typical real use is scrolling to an item right after adding it, because the item must exist in the DOM first. Treat flushSync as an escape hatch. It costs extra renders and can hurt performance, so do not use it to "fix" stale values. Use updater functions for that.
Common mistakes
- Expecting the setter to change the variable.
setA(a + 1)followed byconsole.log(a)prints the old value. The variable belongs to the current snapshot and never changes. - Reading state after an
awaitand expecting it to be fresh. The closure still holds the snapshot from the render that created the handler. Use an updater function when the new value depends on the old one. - Writing code that depends on a render happening between two setters. After the setters run, React has only queued the update, so a render has not yet happened. If you need to react to state, compute from the values you already have, or derive during render.
- Mixing a value and an updater without tracing the queue. The order matters, as the table above shows.
Exercise
A component has const [count, setCount] = useState(0). A click handler runs setCount(count + 1); setCount(c => c + 10); setCount(count + 2);. What does count hold after the next render, and how many renders does the click cause?
Show answer
count is 2 after the next render, and the click causes one render. The queue is processed in order starting from 0. The first update replaces the state with 0 + 1 = 1. The updater turns 1 into 11. The last update replaces the state with 0 + 2 = 2, because count is the snapshot value 0. The last replacement wins. All three updates are batched into a single render.
Exercise
In React 18 using createRoot, a handler calls setTimeout(() => { setX(1); setY(2); }, 0). How many renders does this cause, and what would the count have been in React 17?
Show answer
In React 18 with createRoot, automatic batching groups both updates, so there is one render. In React 17, updates outside React event handlers were not batched, so setX(1) and setY(2) each caused their own render, for two renders in total.