Sub topic 5
How React Batches State Updates
This chapter assumes you know JavaScript functions and objects, basic React components and JSX, and the useState hook. You should also know that a state update schedules a re-render. Here you will learn how React groups several updates into one render, and how to write updates that work correctly when they are grouped.
What batching means
Batching is React's practice of collecting multiple state updates and applying them in a single re-render. Calling a setter such as setCount does not change the variable immediately. It adds the update to a queue. React processes the queue after your event handler finishes, then renders once.
Since React 18, this applies to every update source: event handlers, timeouts, promises, and native event handlers. Earlier versions batched only inside React event handlers.
State is a snapshot
Each render sees fixed values for its props and state. Inside a handler, the variable count keeps the value it had when that render happened, even after you call setCount.
This explains a common error. The next example has two buttons.
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 the queue holds "replace with 1" twice. The result is 1. In addTwoRight, you pass an updater function. React calls each one in order with the latest pending value, so the result is 2.
How the queue is processed
When React renders, it takes the state's starting value and applies each queued item in order.
| Queued item | Value before | Value after |
|---|---|---|
| `setCount(5)` | 0 | 5 |
| `setCount(c => c + 1)` | 5 | 6 |
| `setCount(10)` | 6 | 10 |
The last item wins here because setCount(10) ignores the previous value. Plain values replace the state. Updater functions transform it.
Batching across different state variables
Updates to separate useState variables are batched together too. This avoids partial screens where one value has changed and another has not.
import { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const [submitted, setSubmitted] = useState(false);
console.log('Form rendered', { name, submitted });
function handleSubmit() {
setName('');
setSubmitted(true);
// One render logs once, with both new values.
}
return (
<button onClick={handleSubmit}>
{submitted ? 'Done' : 'Submit'}
</button>
);
}The console prints once per click, not twice.
Common errors
- Reading state right after setting it.
setCount(count + 1); console.log(count);logs the old value. Compute the next value in a local variable if you need it right away. - Using the plain form when the update depends on the previous value. Use
setCount(c => c + 1)when several updates may run before the next render. - Mutating state objects. React compares by reference. Call
setUser({ ...user, name })instead of changinguser.namedirectly. - Expecting each setter call to render. Only one render happens per batch. Do not rely on seeing intermediate states.
Opting out with flushSync
Rarely, you need the DOM updated before the next line of code runs. flushSync from react-dom forces a synchronous render for the updates inside it.
import { flushSync } from 'react-dom';
function addItem(setItems, listRef, item) {
flushSync(() => {
setItems(items => [...items, item]);
});
// The DOM now contains the new item.
listRef.current.lastChild.scrollIntoView();
}Use it sparingly, because it gives up the efficiency of batching.
Exercise
A component has const [count, setCount] = useState(0). A click handler runs setCount(count + 5); setCount(c => c + 1); setCount(count + 10);. What is count after the next render, and how many renders happen?
Show answer
count is 10 and one render happens. The queue applies in order: the first call sets 5, the updater makes it 6, and the last call replaces it with 10 because count was 0 in this render's snapshot. All three calls are batched into a single render.