Sub topic 5
Using useReducer and dispatch in a component
This chapter assumes you know JavaScript functions, objects, arrays, and spread syntax. It also assumes you can write React function components and use useState. Earlier chapters covered the reducer function, action objects, and immutable updates. Here you connect them to a component.
The shape of the hook
useReducer takes a reducer and an initial state. It returns a pair: the current state and a dispatch function.
const [state, dispatch] = useReducer(reducer, initialState);reduceris a function(state, action) => nextState.initialStateis the valuestatehas on the first render.stateis the value for the current render.dispatch(action)asks React to run the reducer with the current state and the action you pass.
The component never changes state itself. It only describes what happened, and the reducer decides the result.
A complete counter
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>
</>
);
}The reducer sits outside the component. It does not read props or other component values, so it is created once and can be moved to its own file.
Each button's handler passes an action object to dispatch. The handler contains no update logic. All the rules for changing the count live in counterReducer.
What happens when you dispatch
Dispatching does not change state in the code that is already running. The new value appears on the next render. This surprises many people:
function handleClick() {
dispatch({ type: 'incremented' });
console.log(state.count); // still the old value in this handler
}Each render has its own state. The handler closed over the one from the render in which it was created.
Actions carry data
An action is a plain object. The type field says what happened. Extra fields carry the data the reducer needs.
dispatch({ type: 'added', id: nextId++, text });Name types after the event ("added", "toggled") rather than the setter you imagine ("setTodos"). A reducer then reads as a log of things that happened.
Updating arrays and objects
When the state is an array or object, each case must return a new value. Use spread, map, and filter, and do not mutate the old state.
import { useReducer, useState } from 'react';
function todosReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: action.id, text: action.text, done: false }];
case 'toggled':
return todos.map(t =>
t.id === action.id ? { ...t, done: !t.done } : t
);
case 'deleted':
return todos.filter(t => t.id !== action.id);
default:
throw Error('Unknown action: ' + action.type);
}
}
let nextId = 0;
export default function TodoApp() {
const [todos, dispatch] = useReducer(todosReducer, []);
const [text, setText] = useState('');
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<button
onClick={() => {
dispatch({ type: 'added', id: nextId++, text });
setText('');
}}
>
Add
</button>
<ul>
{todos.map(t => (
<li key={t.id}>
<label>
<input
type="checkbox"
checked={t.done}
onChange={() => dispatch({ type: 'toggled', id: t.id })}
/>
{t.text}
</label>
<button onClick={() => dispatch({ type: 'deleted', id: t.id })}>
Delete
</button>
</li>
))}
</ul>
</>
);
}This component mixes both hooks on purpose. The todo list uses useReducer because several actions change it. The text in the input uses useState because it is a single value with one way to change. Using both in one component is normal.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Calling the reducer: `onClick={dispatch({ type: 'reset' })}` | Dispatches during render and can loop | Wrap it: `onClick={() => dispatch(...)}` |
| Mutating state: `state.count++; return state;` | React sees the same object and may skip the re-render | Return a new object |
| No `default` case or no `return` in a case | State becomes `undefined` | Return in every case and throw in `default` |
| Passing the reducer call: `useReducer(counterReducer(), ...)` | Wrong arguments to the hook | Pass the function itself |
Exercise
A component calls dispatch({ type: 'incremented' }) and then logs state.count on the next line of the same click handler. Why does the log show the old count, and when does the new count appear?
Show answer
state is fixed for each render, and the handler closed over the state of the render that created it. dispatch only queues an update. React runs the reducer and re-renders, and the new count is available in state during that next render.
Exercise
Add a 'cleared' action to todosReducer that removes every todo whose done is true. What does the case return?
Show answer
case 'cleared': return todos.filter(t => !t.done); It returns a new array and leaves the old one unchanged.