Sub topic 7
How React batches multiple updates
This chapter assumes you can declare state with useState, call setters from event handlers, and that you know state is a snapshot for each render. Here you will see how several setter calls become one re-render.
Calls queue, then render once
A setter does not re-render the component right away. It adds an update to a queue. React waits until the running code has finished, then processes the whole queue and renders once. This is called batching.
import { useState } from 'react';
function Greeting() {
const [name, setName] = useState('');
const [count, setCount] = useState(0);
console.log('render');
function handleClick() {
setName('Ada');
setCount(c => c + 1);
setCount(c => c + 1);
}
return (
<button onClick={handleClick}>
{name} {count}
</button>
);
}One click calls three setters, but the console prints render only once more. The button then shows Ada 2.
Why batching helps
- Fewer renders. Rendering is the costly step, so one render per event is cheaper than one per setter.
- Consistent screens. The user never sees a half-updated UI, such as the new
namenext to the oldcount.
Batching and snapshots
Batching is why a handler's count does not change after you call setCount. The queued update is applied on the next render, not inside the running handler. If one update depends on another, use updater functions such as c => c + 1. React runs them in order, and each receives the result of the previous one.
What batching covers
Since React 18, batching is automatic. It applies to updates inside event handlers, setTimeout callbacks, promise callbacks, and native event handlers. Earlier versions batched only inside React event handlers, so an update in a promise callback caused one render per setter.
Batching does not combine separate events. Two clicks are two events, and each click gets its own render. React also does not wait for async work. In the example below, the update before await and the update after it are two separate batches.
async function handleSave() {
setStatus('saving');
await save();
setStatus('saved');
}Common mistakes
- Expecting the variable to change right after the setter call. It keeps the snapshot value until the next render.
- Adding extra state only to "trigger" a re-render. A setter call already schedules one.
- Reading a stale value in a follow-up setter call. Use an updater function instead.
Exercise
A handler calls setA(1), setB(2) and setC(3) in a row, and then logs a. How many renders does this handler cause, and what does the log show?
Show answer
It causes one render, because React batches the three updates until the handler finishes. The log shows the old value of a, because the handler still sees the snapshot from the render that created it.