Sub topic 3
Describing changes with actions
This chapter assumes you know JavaScript objects and the spread operator, React function components, and useState. It also assumes you have seen a reducer's shape, (state, action) => nextState. Here the focus is the second argument: the action.
What an action is
An action is a plain JavaScript object that describes one thing that happened in your app. It does not change anything. It is a message that a reducer reads to decide the next state.
{ type: 'added', id: 3, text: 'Buy milk' }By convention the type field says what happened. Any other fields carry the data the reducer needs. React does not require this shape, but nearly every codebase and tool follows it.
Name actions after events
Name an action for what the user did, not for the state change you want. Compare these two.
{ type: 'set_todos', todos: [...] }tells the reducer to store a value. The event handler has already done the thinking.{ type: 'deleted', id: 3 }says what happened. The reducer decides how state changes.
Event-style names keep the logic in one place. If the rule for deleting changes later, you edit the reducer and leave every call site alone. Past-tense names such as added, toggled, and deleted also read well in a log.
Carrying data with a payload
Put in the action only the data the reducer cannot work out itself. A form reducer shows the pattern.
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 'form_cleared':
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>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
<button type="button" onClick={() => dispatch({ type: 'form_cleared' })}>
Clear
</button>
</form>
);
}One field_changed action serves every input, because it carries field and value. The form_cleared action needs no payload at all, since the reducer already knows the initial state.
Some teams group the extra data under one key, such as { type: 'added', payload: { id, text } }. Others use flat fields, as above. Either works. Pick one style and use it everywhere.
Where to create the data
Build any random or time-dependent values in the event handler, not in the reducer. Examples are IDs from a counter, Date.now(), and crypto.randomUUID(). The reducer must return the same result for the same inputs, and these values would break that rule. The handler creates the ID and puts it in the action.
dispatch({ type: 'added', id: crypto.randomUUID(), text });Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Dispatching a string, such as `dispatch('added')` | `action.type` is `undefined`, so the reducer hits its `default` case | Dispatch an object with a `type` field |
| Passing the reducer's return value to `dispatch` | The reducer receives a state object as its action | Dispatch only action objects |
| Misspelling a type string | The `default` case throws `Unknown action` | Keep type strings in one place, or use TypeScript |
| Putting the whole next state in the action | The reducer only copies it, and the logic stays in handlers | Send the event and its inputs |
| Mutating the action inside the reducer | Hard-to-trace bugs, since actions may be reused | Treat the action as read-only |
One action per event
When one user event changes several fields, dispatch one action. Do not dispatch several in a row. A checkout_completed action can reset the cart and set an order number in one step. The reducer then never produces a state where the cart is empty but the order number is missing.
Exercise
A "Mark all done" button should set done: true on every todo. Which is better: dispatch({ type: 'set_todos', todos: todos.map(t => ({ ...t, done: true })) }) or dispatch({ type: 'all_marked_done' })? Explain why.
Show answer
The second. It describes the event and carries no data, so the reducer owns the rule for what "all done" means. The first computes the next state in the handler and makes the reducer a passive setter. It also builds the update from the todos value captured at render time, which may be stale.
Exercise
A reducer for a note list needs a unique ID for each new note. Where should the ID be created, and why?
Show answer
In the event handler, before dispatching, and it goes into the action as a field such as id. The reducer must be pure, and calling something like crypto.randomUUID() inside it would give different results for the same state and action.