How does React batch state updates, and how do you control it?
Hint
Since React 18, batching is automatic. Which API forces an update out of a batch, and which old one is no longer needed?
Full Answer
React batches state updates: several setState calls in the same tick produce one re-render. Since React 18 (with createRoot) this happens everywhere — event handlers, timeouts, promises and native listeners.
// One re-render for both updates — no extra API needed
async function save() {
const data = await api.save();
setSaving(false);
setResult(data);
}
// Opt out: apply this update immediately
import { flushSync } from 'react-dom';
flushSync(() => setOpen(true));
// DOM is updated here
unstable_batchedUpdateswas the React 17 workaround for batching outside event handlers. In React 18+ it's unnecessary.flushSyncdoes the opposite of batching: it forces the updates inside it to render synchronously.useMemo/useCallbackdon't batch anything. They reduce the cost of each render by keeping values stable for memoized children.
💡 To cut re-renders further, put related state in one object or a reducer, and keep state as close as possible to where it's used.
More React Fundamentals Questions
Practice this in a timed sprint
5 free questions, no signup required