Sub topic 10
How dispatch behaves: identity, batching, and bail-out
This chapter assumes you can write a reducer, dispatch action objects from event handlers, and update state immutably. You should also know that React re-renders a component after its state changes. Here you will learn three behaviors of dispatch that decide whether your component renders when and how often you expect: it has a stable identity, it batches updates, and it can bail out of a render.
Dispatch schedules an update, it does not run one
Calling dispatch(action) does not change state in the code that is currently running. It queues the action. React then calls your reducer during the next render and gives the component the result.
Inside an event handler, state is a snapshot from the render that created the handler. Dispatching does not change that snapshot.
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Triple() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
function handleClick() {
dispatch({ type: 'incremented' });
dispatch({ type: 'incremented' });
dispatch({ type: 'incremented' });
console.log(state.count); // still the count from this render
}
return (
<>
<p>Count: {state.count}</p>
<button onClick={handleClick}>+3</button>
</>
);
}On the first click, the console prints 0 and the screen then shows 3. All three actions were queued, and the reducer processed them in order against the latest state: 0 to 1, 1 to 2, 2 to 3. Each action sees the result of the one before it. This is why reducers avoid the stale-state problem that setCount(count + 1) can cause with useState.
Batching: many dispatches, one render
React groups state updates that happen in the same tick and renders once afterward. In the example above there were three dispatches and one render.
Since React 18, this automatic batching applies everywhere, not only in React event handlers. That includes promise callbacks, setTimeout callbacks, and native event handlers.
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'loaded':
return { ...state, items: action.items, loading: false };
case 'counted':
return { ...state, total: action.total };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function List() {
const [state, dispatch] = useReducer(reducer, {
items: [],
total: 0,
loading: true,
});
console.log('render', state.items.length, state.total);
function load() {
setTimeout(() => {
dispatch({ type: 'loaded', items: ['a', 'b'] });
dispatch({ type: 'counted', total: 2 });
}, 100);
}
return (
<>
<button onClick={load}>Load</button>
<p>{state.loading ? 'Waiting' : state.items.join(', ')}</p>
<p>Total: {state.total}</p>
</>
);
}After the timeout fires, the console logs render 2 2 once. It never logs a half-updated render 2 0. The user never sees a frame where the items have loaded but the total is stale.
Batching also gives you a design rule. When two fields must always change together, put them in one action so the reducer updates them in a single step. Relying on two separate dispatches works in practice, but one action states the intent directly.
Forcing a synchronous render
Rarely, you need the DOM to be updated before the next line runs, for example to measure an element. flushSync from react-dom forces React to render immediately.
import { flushSync } from 'react-dom';
function handleAdd(dispatch, listRef) {
flushSync(() => {
dispatch({ type: 'added', id: Date.now(), text: 'New item' });
});
// The DOM already contains the new item here.
listRef.current.lastChild.scrollIntoView();
}Use it sparingly. It opts out of batching and can hurt performance.
Dispatch has a stable identity
React returns the same dispatch function on every render for the lifetime of the component. Its identity never changes, even when state does. This has three consequences:
- You can pass
dispatchto memoized children without breakingReact.memo. - You can put
dispatchin auseEffectoruseCallbackdependency array without re-running the effect. - You can read it from a context and know the context value will not change.
The following effect subscribes once. It never has a stale-closure problem, because it only dispatches and never reads state.
import { useEffect, useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'ticked':
return { seconds: state.seconds + 1 };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Timer() {
const [state, dispatch] = useReducer(reducer, { seconds: 0 });
useEffect(() => {
const id = setInterval(() => dispatch({ type: 'ticked' }), 1000);
return () => clearInterval(id);
}, [dispatch]);
return <p>{state.seconds} seconds</p>;
}The react-hooks/exhaustive-deps lint rule knows that dispatch from useReducer is stable. You may list it or leave it out. Listing it is harmless, and it keeps the rule satisfied if you later receive dispatch as a prop, where the linter cannot know it is stable.
Note what stays stable and what does not. dispatch is stable, but a handler you build around it, such as () => dispatch({ type: 'reset' }), is a new function every render.
Bail-out: when a dispatch changes nothing
After React calls your reducer, it compares the result with the current state using Object.is. If they are the same value, React skips re-rendering the children and does not run effects for that update. This is called a bail-out.
You can use it on purpose by returning the existing state for actions that change nothing.
import { useReducer } from 'react';
function filterReducer(state, action) {
switch (action.type) {
case 'filter_set':
if (state.filter === action.filter) {
return state; // nothing changed, so keep the same object
}
return { ...state, filter: action.filter };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Filters() {
const [state, dispatch] = useReducer(filterReducer, { filter: 'all' });
console.log('render', state.filter);
return (
<>
<p>Filter: {state.filter}</p>
{['all', 'open', 'done'].map(f => (
<button key={f} onClick={() => dispatch({ type: 'filter_set', filter: f })}>
{f}
</button>
))}
</>
);
}Clicking open twice in a row renders once. The second click returns the same state object, so React bails out.
Bail-out is also the source of a classic bug
The same rule causes silent failures when you mutate state. If a reducer changes the existing object and returns it, the result is identical to the old state, so React bails out and the screen does not update.
// Bug: mutates the array and returns the same reference
function badReducer(state, action) {
switch (action.type) {
case 'added':
state.items.push(action.item);
return state; // Object.is(old, new) is true, so no re-render
default:
return state;
}
}The fix is to return a new object, as in the immutable-updates chapter: return { ...state, items: [...state.items, action.item] };.
The bail-out is not always instant
React may call your component function one more time before it decides to bail out. It will not render the children or commit anything, but a console.log in the component body can still appear once. Do not put side effects in the render body and expect them to be skipped. Keep render code pure, as with the reducer.
Reducers run during render
React runs your reducer while it renders the component, not at the moment you call dispatch. Three things follow:
- The reducer must be pure. In development, Strict Mode calls it twice with the same inputs to expose impure code, and it discards one result. If your reducer logs, generates IDs, or mutates, you will see the difference.
- Put IDs and timestamps in the action, not in the reducer. In the todo example,
dispatch({ type: 'added', id: nextId++, text })creates the ID in the event handler, where it runs once. - The reducer can read the latest props. React uses the reducer function from the current render, so a reducer defined inside the component can close over props. Doing this is allowed, but it makes the reducer harder to test and reuse. Prefer passing the values in the action.
Edge cases
- Dispatch after unmount. React 18 does not warn and does nothing. You still should cancel timers and subscriptions in the effect cleanup, because the work behind them is wasted.
- Dispatch during render. Calling
dispatchfor the same component while it renders is allowed, and React restarts the render immediately. It is meant for rare derived-state patterns. If you do this without a condition that stops it, you get an infinite loop. - Unknown actions. Throwing in the
defaultcase, as the examples do, surfaces typos such as'incrmented'at once. An error thrown in a reducer during render is handled like any render error and reaches the nearest error boundary.
| Behavior | What it means | Practical rule |
|---|---|---|
| Queued update | `state` in the current handler does not change after `dispatch` | Read the new state in the next render |
| Batching | Several dispatches in one tick give one render | Group fields that change together into one action |
| Stable identity | `dispatch` is the same function every render | Safe in dependency arrays and context |
| Bail-out | A result identical to the old state skips children and effects | Return `state` for no-ops, never mutate it |
| Render-time reducer | Reducers run while rendering, twice in Strict Mode | Keep them pure and put impure values in the action |
Exercise
A component uses useReducer with a reducer that adds 1 to state.count for { type: 'incremented' }. A click handler runs dispatch({ type: 'incremented' }); dispatch({ type: 'incremented' }); console.log(state.count); and state.count was 4 before the click. What does the console print, how many renders happen, and what count is shown afterward?
Show answer
The console prints 4, because state is the snapshot from the render that created the handler. Batching gives one re-render. The reducer processes both actions in order, so the screen shows 6.
Exercise
A teammate writes a reducer case case 'cleared': state.items.length = 0; return state;. The list on screen does not clear. Explain why, and fix the case.
Show answer
The case mutates the existing object and returns it, so Object.is(oldState, newState) is true and React bails out without re-rendering. Return a new object instead: case 'cleared': return { ...state, items: [] };.