Sub topic 5
Using useReducer and dispatch in a component
This chapter shows how to call useReducer in a component and how dispatch connects event handlers to the reducer. It assumes you can write a reducer function that takes (state, action) and returns the next state, and that you know how action objects carry a type and extra fields. It also assumes you know useState and why state changes trigger a re-render.
The shape of the call
useReducer is a built-in React hook. You call it at the top level of a function component, and it returns a pair.
const [state, dispatch] = useReducer(reducer, initialArg, init);| Part | What it is |
|---|---|
| `reducer` | A function `(state, action) => nextState`. You define it, usually outside the component. |
| `initialArg` | The starting state. If you also pass `init`, it is the value handed to `init`. |
| `init` | Optional. A function that computes the starting state from `initialArg`. A later chapter covers it. |
| `state` | The current state for this render. |
| `dispatch` | A function that takes one action and asks React to run the reducer with it. |
The hook follows the usual rules. Call it at the top level, not inside loops, conditions, or nested functions. React tracks hooks by call order, so the call order must be the same on every render.
A complete example
This counter shows the full cycle.
import { useReducer } from 'react';
function counterReducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'decremented':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'incremented' })}>+1</button>
<button onClick={() => dispatch({ type: 'decremented' })}>-1</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</>
);
}Three things to notice:
- The reducer lives outside the component. It does not need props or other component variables, so it does not have to be recreated on every render. It is also easy to move into its own file and test.
- The event handlers contain no update logic. They only say what happened:
incremented,decremented,reset. - The state is an object,
{ count }, so the component readsstate.count. State can be any value, including a number, array, or object.
What happens when you call dispatch
dispatch does not change state immediately and does not return the new state. It queues the action and schedules a re-render. React then runs your reducer during the next render and uses its result as the new state.
This ordering explains one of the most common surprises. Inside the handler, state is still the value from the render that created the handler.
function handleClick() {
dispatch({ type: 'incremented' });
console.log(state.count); // still the old count
}Each render has its own state snapshot. If you need the new value, compute it by calling the reducer yourself, or read it in the next render. Do not expect it right after dispatch.
Dispatching with payloads
Actions carry whatever data the reducer needs. Put it in extra fields on the action. Some codebases use a single payload field, and others use named fields. Either works if you are consistent.
A form with several text inputs shows why one action can serve many fields.
import { useReducer } from 'react';
const initialForm = { name: '', email: '' };
function formReducer(state, action) {
switch (action.type) {
case 'field_changed':
return { ...state, [action.field]: action.value };
case 'reset':
return initialForm;
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function SignupForm() {
const [form, dispatch] = useReducer(formReducer, initialForm);
function handleChange(e) {
dispatch({
type: 'field_changed',
field: e.target.name,
value: e.target.value,
});
}
return (
<form
onSubmit={e => {
e.preventDefault();
alert('Welcome, ' + form.name + ' <' + form.email + '>');
dispatch({ type: 'reset' });
}}
>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
<button type="submit">Sign up</button>
</form>
);
}The action object is built when handleChange runs, so it reads e.target.name and e.target.value at that moment. The reducer later receives plain values and never touches the event. Build the action from the event inside the handler. Do not pass the event object into the reducer.
The [action.field] syntax is a computed property name. The reducer copies the old fields with spread and overwrites one of them. The result is a new object, which React needs to detect the change.
Where to call dispatch
You can call dispatch from any code that runs after render:
- Event handlers such as
onClick,onChange, andonSubmit. - Effects inside
useEffect, for example to record that a fetch started or finished. - Timers, promise callbacks, and subscriptions set up in effects.
- Child components, when you pass
dispatchdown as a prop or share it through context.
Do not call it unconditionally during rendering. That queues an update during render, and the update causes another render, which calls dispatch again. React will stop this with a "Too many re-renders" error.
Common errors
Calling dispatch while writing the handler
// Wrong: runs during render, not on click
<button onClick={dispatch({ type: 'incremented' })}>+1</button>The expression dispatch({ ... }) runs immediately while React builds the JSX, and its return value, undefined, becomes the click handler. Wrap the call in a function.
// Right
<button onClick={() => dispatch({ type: 'incremented' })}>+1</button>Passing the reducer call result instead of the reducer
// Wrong: calls the reducer once, with no state or action
const [state, dispatch] = useReducer(counterReducer(), { count: 0 });
// Right: pass the function itself
const [state, dispatch] = useReducer(counterReducer, { count: 0 });Passing the whole action creator to dispatch
dispatch takes an action. It does not take a function that returns an action. If you write a helper such as const increment = () => ({ type: 'incremented' }), you must call dispatch(increment()), not dispatch(increment).
Forgetting to return in a case
If a case runs without returning, the reducer returns undefined, and your state becomes undefined. The next render then fails when it reads state.count. Check that every case returns a complete state value.
// Wrong: the return is missing
case 'incremented':
{ count: state.count + 1 };Returning a partial state
Unlike the class-component setState, a reducer's return value replaces the whole state. It is not merged. If your state has several fields, every case must produce all of them, usually with { ...state, changed: value }.
// Wrong: loses 'email'
case 'name_changed':
return { name: action.value };
// Right
case 'name_changed':
return { ...state, name: action.value };Mutating state
// Wrong: mutates the existing object and returns it
case 'incremented':
state.count++;
return state;React compares the returned value with the previous state using Object.is. If you return the same object, React sees no change and skips the re-render. The screen will not update, which is hard to debug. Always return a new object or array when something changed.
Typos in action types
A misspelled type such as 'incrmented' reaches the default branch. That is why the reducers in this chapter throw an error there. Failing loudly is better than silently ignoring an action. A TypeScript chapter later shows how the compiler can catch these typos.
Reading state and dispatching together
A component often needs both: it reads state to render and calls dispatch to change it. Because dispatch takes no state argument, handlers rarely need state just to compute updates. Compare the two styles.
// useState style: the handler computes the new value
setCount(count + 1);
// useReducer style: the handler describes the event
dispatch({ type: 'incremented' });With the reducer, the rule for "how does a count increment" exists in one place. The handler does not need the current count, so it also cannot use a stale one.
A quick check of the lifecycle
Use this list when a reducer-based component misbehaves:
- Is
dispatchcalled inside a function that runs on an event, not during render? - Does the action have a
typethat matches a case exactly? - Does that case return a complete state value, not
undefinedand not a partial object? - Does it return a new object or array when something changed?
- Are you reading
stateright afterdispatchand expecting the new value?
Most reducer bugs fail one of these five checks.
Summary of what you can now do
- Call
useReducer(reducer, initialState)and destructure[state, dispatch]. - Wire event handlers to
dispatchwith arrow functions, building action objects from event data. - Explain that
dispatchqueues work and that the reducer runs during the next render. - Recognize the common failures: calling
dispatchat render time, returning partial or mutated state, and forgetting a return.
Exercise
This component never changes its count when the button is clicked, and the console shows an error about too many re-renders. Find the two problems and fix them. function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return <button onClick={dispatch({ type: 'incremented' })}>{state.count}</button>; } function reducer(state, action) { if (action.type === 'incremented') { state.count++; return state; } return state; }
Show answer
First, dispatch({ type: 'incremented' }) is called while the JSX is built, so it runs on every render and triggers another render. Wrap it: onClick={() => dispatch({ type: 'incremented' })}. Second, the reducer mutates state and returns the same object, so React sees no change with Object.is and skips the update. Return a new object instead: return { count: state.count + 1 };. The reducer should also throw on unknown action types rather than silently returning state.
Exercise
A handler runs dispatch({ type: 'incremented' }); alert(state.count); and the alert shows the count from before the click. Why, and how can you get the new count?
Show answer
state is a snapshot from the render that created the handler. dispatch only queues an action and schedules a new render, so the reducer has not run yet when alert runs. To use the new value, read state.count in the next render, for example in JSX or an effect. You can also call the reducer yourself to compute the next state inside the handler: const next = counterReducer(state, action).