React’s useState hook adds state to function components. When you call the state setter returned by useState (conventionally named setState), React schedules an update for the component. Those updates don’t always run immediately, though. React has a batching mechanism that merges multiple state updates to cut down on needless re-renders and keep the app fast. How that mechanism works — and how it can bite you — is something every React developer should understand.
How Batching Works
- Batching in event handlers: state updates triggered inside React event handlers (say, a button’s onClick) are batched automatically. If you call
setStateseveral times in a row within one handler, React merges those updates into a single one and re-renders just once. This applies to updates in React-managed handlers likeonClickandonChange. - Batching in async code: React 18 introduced automatic batching, so state updates inside async operations (
setTimeoutcallbacks,Promise.then, or any async callback not triggered by a React event) are batched too. In React 17 and earlier, only updates inside React-controlled event handlers were batched; updates in async code were not. - Manual batching: when you need to force batching where it doesn’t happen automatically (for instance, in async code on React 17 or older), reach for
ReactDOM.unstable_batchedUpdates(). Wrapping your updates in its callback batches them even inside async operations.
What Batching Means for You
- Better performance: fewer re-renders means batching can noticeably improve app performance.
- Updates get merged: while a batch is open, React merges state updates. Update the same state multiple times and only the last update wins.
- Asynchrony:
setStatecalls are asynchronous — React applies the new state at some later point. Reading the state right after callingsetStatemay not reflect the latest value.
The Case
Suppose you have a page with two child components. On page initialization it needs to call an API whose two parameters are emitted by those two children via events. Pseudocode:
import React, { useState, useEffect } from 'react';
const ChildrenOne = (props) => { useEffect(() => { setTimeout(() => { props.onSendMsg('one'); }, Math.random() * 3 * 1000); }, []); return <></>;};const ChildrenTwo = (props) => { useEffect(() => { setTimeout(() => { props.onSendMsg('two'); }, Math.random() * 3 * 1000); }, []); return <></>;};
export default () => { const [params, setParams] = useState({ msg1: '', msg2: '', }); const onSearch = () => { console.log(params); }; const onEmitOne = (msg: string) => { setParams({ ...params, msg1: msg, }); }; const onEmitTwo = (msg: string) => { setParams({ ...params, msg2: msg, }); }; useEffect(() => { // Should only run once both msg1 and msg2 are ready if (params.msg1 && params.msg2) { onSearch(); } }, [params]); return ( <> <ChildrenOne onSendMsg={onEmitOne} /> <ChildrenTwo onSendMsg={onEmitTwo} /> </> );};You’ll notice onSearch never fires. That’s because setParams is asynchronous, and every call builds on the stale params snapshot. Inside onEmitOne and onEmitTwo, the value of params was captured when the function started running and won’t change no matter what state updates happen. So when the two functions run at nearly the same time, both read the initial state — meaning that even though both call setParams, the final state contains only one function’s update. The fix is to use the functional form of setParams, which always receives the latest state.
To solve it, switch setParams to its functional form — the updater function always gets the freshest state:
const onEmitOne = (msg: string) => { setParams(prevParams => ({ ...prevParams, msg1: msg, }));};const onEmitTwo = (msg: string) => { setParams(prevParams => ({ ...prevParams, msg2: msg, }));};Now whenever onEmitOne and onEmitTwo fire, setParams builds on the latest state, so onSearch is guaranteed to trigger.
That gets onSearch firing — but now a new problem: any later change to those parameters fires the API call again, and again. My requirement was to fetch only once, at page initialization.
My solution: turn onEmitOne and onEmitTwo into async functions that pass their results out through a Promise, then add a new getInitData function that runs only on mount. It collects the two values emitted by the children, hands them to onSearch, and runs it. onSearch in turn gets reshaped to accept parameters:
export default () => { const [params, setParams] = useState({ msg1: '', msg2: '', }); const onSearch = (_param?: { msg1: string; msg2: string }) => { const { msg1, msg2 } = _param ?? {}; const param = { msg1: msg1 ?? params.msg1, msg2: msg2 ?? params.msg2, }; setParams({ ...params, ...param, }); console.log(param); }; const onEmitOne = async (msg: string): Promise<string> => { return new Promise((resolve) => { resolve(msg); }); }; const onEmitTwo = async (msg: string): Promise<string> => { return new Promise((resolve) => { resolve(msg); }); }; const getInitData = async () => { const res = await Promise.all([onEmitOne('one'), onEmitTwo('two')]); onSearch({ msg1: res[0], msg2: res[1], }); }; useEffect(() => { getInitData(); }, []); return <></>;};