Sub topic 5
How React Batches State Updates
This chapter assumes you know JavaScript functions, objects, and arrays, the basics of React components, props, and JSX, and how to use the useState hook. You should also know that a state update schedules a re-render, which the previous chapter on what triggers a re-render covered.
What batching is
Batching means React groups several state updates into one re-render. React does not re-render after every call to a setter function such as setCount. It collects the updates, then renders once with the final result.
Batching matters for two reasons. It avoids wasted work, because rendering a component and its children can be expensive. It also keeps the screen consistent, because the user never sees a half-updated state, such as a new name paired with an old email.
Updates are requests, not assignments
A call to setCount(5) does not change count right away. It adds a request to a queue and asks React to render again. The variable count in the current render is a snapshot. It keeps its value until the next render.
import { useState } from 'react';
function Snapshot() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // still the old value, for example 0
}
return <button onClick={handleClick}>Count: {count}</button>;
}The console.log prints the old value. The handler function closed over count from the render that created it, and that value never changes inside that render.
Batching inside one event handler
React processes all updates made in one event handler after the handler finishes. Here is the two-setter example from earlier chapters, with several fields.
import { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
console.log('Form rendered');
function fill() {
setName('Ada');
setEmail('[email protected]');
// One render follows, not two.
}
return (
<>
<button onClick={fill}>Fill</button>
<p>{name} / {email}</p>
</>
);
}Clicking the button logs Form rendered once. Both updates sit in the queue, and React applies both before it renders.
The same-value trap
When you call the same setter twice with a value computed from the current snapshot, both calls use the same number.
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
function addTwoWrong() {
setCount(count + 1);
setCount(count + 1); // both use the same count from this render
}
function addTwoRight() {
setCount(c => c + 1);
setCount(c => c + 1); // updater functions queue up and apply in order
}
return (
<>
<p>{count}</p>
<button onClick={addTwoWrong}>+2 (actually +1)</button>
<button onClick={addTwoRight}>+2</button>
</>
);
}In addTwoWrong, count is 0 in both calls, so both requests say "set the state to 1". The result is 1.
In addTwoRight, you pass an updater function. An updater function is a function that receives the pending state and returns the next state. React stores these functions in the queue and runs them in order during the next render. The first receives 0 and returns 1. The second receives 1 and returns 2.
How the queue is processed
For each state variable, React keeps a queue of updates. During the render, it starts from the previous state and walks the queue.
| Call | What is queued | State after processing |
|---|---|---|
| `setCount(5)` | Replace with 5 | 5 |
| `setCount(n => n + 1)` | Run this function | 6 |
| `setCount(42)` | Replace with 42 | 42 |
If you queue these three calls in this order, the final state is 42. A plain value replaces whatever came before it. An updater function transforms whatever came before it.
import { useState } from 'react';
function Queue() {
const [number, setNumber] = useState(0);
return (
<button
onClick={() => {
setNumber(number + 5); // replace with 5
setNumber(n => n + 1); // 5 -> 6
setNumber(42); // replace with 42
}}
>
{number}
</button>
);
}After one click, the button shows 42.
Rules for updater functions
- Write them as pure functions. They must only compute the next state from the pending state. In Strict Mode, React may call them twice to check this.
- Name the argument after the state, using the first letter or the full name, such as
c => c + 1orcount => count + 1. - Use an updater whenever the next value depends on the previous one. A plain value is fine when it does not, such as
setName('Ada').
A diagram of the flow
Batching across different events
React batches updates inside one event. It does not batch across separate events. Two clicks are two separate events, and each one gets its own render. React finishes the render and commit from the first click before it handles the second, so state from the first click is already visible when the second handler runs.
This design avoids a class of bugs. For example, if a click handler disables a button after a form submits, a second click on that button cannot run before the first update is on screen.
Automatic batching in React 18
Before React 18, batching worked only inside React event handlers. Updates inside a setTimeout, a promise callback, or a native event handler caused one render per setter call. React 18 introduced automatic batching, which groups updates wherever they originate.
import { useState } from 'react';
function Delayed() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
console.log('Delayed rendered');
function handleClick() {
setTimeout(() => {
setCount(c => c + 1);
setFlag(f => !f);
// React 18: one render. React 17: two renders.
}, 1000);
}
return (
<button onClick={handleClick}>
{count} {String(flag)}
</button>
);
}Automatic batching applies only when your app creates its root with createRoot from react-dom/client. An app that still uses the legacy ReactDOM.render keeps the old behavior.
import { createRoot } from 'react-dom/client';
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(<App />);Async code and the snapshot
Batching also covers updates that follow an await. Each await splits your function in parts. Updates made in the same part are batched together.
import { useState } from 'react';
function Loader() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
async function load() {
setLoading(true);
const response = await fetch('/api/data');
const json = await response.json();
setData(json);
setLoading(false); // batched with setData
}
return (
<>
<button onClick={load} disabled={loading}>Load</button>
<pre>{JSON.stringify(data)}</pre>
</>
);
}The first setLoading(true) runs before the first await, so React renders for it. The last two setters run together, so the user never sees data with the loading flag still on.
Opting out with flushSync
Rarely, you need the DOM to reflect a state update right away. For example, you may need to scroll to an element that you just added. flushSync from react-dom forces React to process the updates inside its callback and update the DOM before the next line runs.
import { useState, useRef } from 'react';
import { flushSync } from 'react-dom';
function Messages() {
const [messages, setMessages] = useState([]);
const listRef = useRef(null);
function add() {
flushSync(() => {
setMessages(prev => [...prev, `Message ${prev.length + 1}`]);
});
// The new <li> is in the DOM here.
listRef.current.lastChild.scrollIntoView();
}
return (
<>
<button onClick={add}>Add</button>
<ul ref={listRef}>
{messages.map(m => <li key={m}>{m}</li>)}
</ul>
</>
);
}Common errors
- Reading state right after setting it. The variable still holds the old value. Compute the next value in a local variable and use it for both the setter and the follow-up code.
- Using a plain value for a dependent update. Repeated
setCount(count + 1)calls collapse into one increment. Use the updater form. - Mutating state. Pushing into an array held in state and calling the setter with the same array gives React nothing new to compare. Create a new array or object each time.
- Side effects in updaters. Updater functions must be pure. Do not call other setters or write to the network inside them.
- Expecting one render per setter. Count renders, not setter calls. A handler with five setters still renders once.
- Same value, no render. If you set state to a value equal to the current one, as judged by
Object.is, React may skip re-rendering the children. It can still call your component once more before it bails out.
Fixing the stale value problem
import { useState } from 'react';
function Total() {
const [total, setTotal] = useState(0);
function addPrice(price) {
const next = total + price;
setTotal(next);
console.log('New total will be', next); // correct value
}
return <button onClick={() => addPrice(10)}>Total: {total}</button>;
}The local variable next holds the value you queued. The log shows what the state will be on the next render.
Where batching fits in the render cycle
Batching sits between the trigger and the render phase. Setters feed the queue, React processes the queue at the end of the event, and the render and commit phases then run once. Later chapters on concurrent rendering build on this. There, React can also split rendering across time, and updates marked as transitions can be interrupted by more urgent ones.
Exercise
A component has const [count, setCount] = useState(0). A click handler runs setCount(count + 1); setCount(c => c + 5); setCount(count + 10);. What does count show after one click, and how many renders happen?
Show answer
It shows 10, after one render. The first call queues "replace with 1". The second queues an updater, which turns 1 into 6. The third queues "replace with 10", because count is still 0 in this render's snapshot. The last plain value wins, so the final state is 10. All three calls are batched into one render.
Exercise
In React 18, a setTimeout callback calls setA(1) and then setB(2). How many renders occur, and why is this different from React 17?
Show answer
One render. React 18 has automatic batching, which groups updates from timeouts, promises, and native events when the app uses createRoot. React 17 batched only inside React event handlers, so these two calls caused two renders.