Sub topic 3
Describing changes with actions
This chapter assumes you can write a reducer function with a switch on action.type. It also assumes you know basic useState, JSX event handlers, and the object spread operator. Here the focus is the action: what it contains, how to name it, and what to leave out of it.
What an action is
An action is a plain JavaScript object that describes one thing that happened in your app. A component hands it to dispatch, and React passes it to your reducer along with the current state. The reducer reads the action and returns the next state.
By convention, an action has a type field, a string that names the event. It can also have extra fields that carry the data the reducer needs.
{ type: 'incremented' }
{ type: 'added', id: 3, text: 'Write tests' }
{ type: 'field_changed', field: 'email', value: '[email protected]' }React does not require the type field. It passes whatever value you dispatch to the reducer unchanged. The type convention exists because a reducer needs some way to tell actions apart, and a string works well with switch.
The action is data, not behavior. It does not contain functions that change state. The reducer holds all the logic, and the action only reports what the user did.
sequenceDiagramThe diagram below shows the path an action takes.
Anatomy of a good action
Name the event, not the setter
You can name actions in two styles. A setter-style name says what to do to the state: set_todos, set_count. An event-style name says what the user did: added, toggled, deleted.
Prefer event names. A setter-style action pushes the logic back into the event handler, which is the problem reducers are meant to solve.
// Setter style: the handler computes the new state
dispatch({ type: 'set_todos', todos: [...todos, newTodo] });
// Event style: the reducer decides what "added" means
dispatch({ type: 'added', id: newTodo.id, text: newTodo.text });With the setter style, the handler needs the current todos array. Every handler that touches todos has to repeat the same update logic. With the event style, the handler only reports the event, and the reducer is the one place that knows how a todo is added.
Many codebases use the past tense (added, toggled) or a noun_verb form (todo_added, fetch_failed). Pick one style and keep it. The names also show up in debugging tools and logs, so a consistent form makes the history of your state readable.
Put the data the reducer needs in extra fields
Two layouts are common for extra data. Both work, so choose one for the whole codebase.
| Layout | Example | Notes |
|---|---|---|
| Flat fields | `{ type: 'added', id: 1, text: 'Milk' }` | Short and easy to read. Used in the React docs. |
| `payload` field | `{ type: 'added', payload: { id: 1, text: 'Milk' } }` | Consistent shape for every action. Common in Redux code. |
The third example in this tutorial's code uses payload for the reset value. Either is fine. Mixing both in one reducer makes it harder to know where to look for data.
Keep the extra fields small. An action should carry the minimum needed to describe the event, such as an id or the typed text. It should not carry data the reducer can already work out from the state.
Let the handler supply ids and other impure values
The reducer must be a pure function: given the same state and action, it must return the same result. If a reducer generates an id, reads the time, or calls Math.random(), it gives different results for the same input. React can call your reducer more than once with the same inputs in development, so impure values cause bugs.
Create values like these in the event handler and send them in the action.
let nextId = 0;
// Wrong: the reducer generates the id, so calling it twice gives different results
function badReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: Math.random(), text: action.text, done: false }];
default:
throw Error('Unknown action: ' + action.type);
}
}
// Right: the handler supplies the id, the reducer only places it
function handleAdd(text, dispatch) {
dispatch({ type: 'added', id: nextId++, text });
}This is why the todo example dispatches { type: 'added', id: nextId++, text }. The reducer then stays easy to test, because the test supplies the id too.
A form with one action for many fields
Actions let you collapse many similar updates into one. Consider a form with several text fields. With useState, you would write one setter and one handler per field. With a reducer, one action can cover all of them.
import { useReducer } from 'react';
const initialForm = { name: '', email: '', subscribed: false };
function formReducer(form, action) {
switch (action.type) {
case 'field_changed':
return { ...form, [action.field]: action.value };
case 'subscription_toggled':
return { ...form, subscribed: !form.subscribed };
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} />
<label>
<input
type="checkbox"
checked={form.subscribed}
onChange={() => dispatch({ type: 'subscription_toggled' })}
/>
Subscribe
</label>
<button type="button" onClick={() => dispatch({ type: 'form_cleared' })}>
Clear
</button>
</form>
);
}Three details are worth noting:
field_changedcarries two pieces of data, the field name and the new value. The computed key[action.field]writes to the right property.subscription_toggledcarries no data at all. The reducer already knows the current value, so the handler should not send it. Sending{ type: 'subscription_toggled', value: !form.subscribed }would copy state logic back into the handler.form_clearedreturnsinitialForm. Returning a shared constant is safe because reducers never mutate it.
The generic field_changed action is a trade-off. It is short, but the reducer will accept any field name, including a typo like emial. If you want the reducer to reject unknown fields, use one action per field, or check action.field against a list of allowed names.
One action, several state changes
An action describes one user event, and that event may change several parts of state at once. This is where reducers improve on separate useState calls.
function checkoutReducer(state, action) {
switch (action.type) {
case 'order_submitted':
return {
...state,
status: 'submitting',
error: null,
attempts: state.attempts + 1,
};
case 'order_failed':
return { ...state, status: 'error', error: action.message };
default:
throw Error('Unknown action: ' + action.type);
}
}A single dispatch({ type: 'order_submitted' }) updates three fields together. Related fields cannot get out of step, because the reducer changes them in one return value. The handler does not need to remember which setters to call.
A useful test for splitting actions is to ask whether a human could describe the event in one sentence. "The user submitted the order" is one action. "The user changed the quantity and the shipping method" is two events, so dispatch two actions, or make a separate action if that combination is a real feature.
Common errors
These mistakes come up often when you start using actions.
- Dispatching a string instead of an object.
dispatch('incremented')runs, butaction.typeisundefinedinside the reducer because a string has notypeproperty. Yourdefaultbranch then throws. Writedispatch({ type: 'incremented' }). - Calling the dispatch result as a state setter.
dispatchreturns nothing. It does not give you the new state. The next value appears on the next render, the same as withuseState. - Typos in the
typestring.'incremeted'falls through to thedefaultcase. Throwing indefault, as every example here does, turns the typo into an immediate error. Without the throw, the reducer silently ignores the action. - Forgetting the extra field. If a handler dispatches
{ type: 'added', text }but the reducer readsaction.id, you getundefinedids. The reducer and the dispatch calls must agree on the shape. TypeScript can enforce this, which a later chapter covers. - Putting the whole event object in the action. Passing
eore.targetcouples the reducer to the DOM. Pull out the values you need (e.target.value) in the handler and send those. - Sending derived values. If the reducer can compute something from the state, do not ask the handler for it. This is the
subscription_toggledcase above.
Keeping the set of actions small and readable
As a reducer grows, the list of action types becomes the public interface of that piece of state. Reading the case labels should tell you everything a user can do to it.
- Group related actions with a shared prefix, such as
fetch_started,fetch_succeeded,fetch_failed. - Define the type strings once if many files use them. A plain object of constants or a TypeScript union both work. Do this only when typos have become a real problem.
- Do not add an action for every possible state change. If two actions run identical reducer code, merge them.
- Keep the reducer's
defaultcase as a throw, so any action you forgot to handle is loud.
Exercise
A shopping cart reducer receives dispatch({ type: 'set_cart', cart: [...cart, item] }) from an "Add to cart" button. Rewrite the dispatch call and the matching reducer case so the action describes the event, and the new item gets its id from the handler rather than the reducer.
Show answer
In the handler: dispatch({ type: 'item_added', id: nextId++, name: item.name }). In the reducer: case 'item_added': return [...cart, { id: action.id, name: action.name }];. The action names the event (item_added) instead of telling the reducer what state to store. The handler no longer needs the current cart. The id is created in the handler, so the reducer stays pure and returns the same result for the same state and action.
Exercise
Why is dispatch({ type: 'subscription_toggled', value: !form.subscribed }) a weaker design than dispatch({ type: 'subscription_toggled' })?
Show answer
The reducer already has the current subscribed value, so it can flip it itself. Computing !form.subscribed in the handler copies update logic into the component. It can also use a stale form value if several dispatches happen before the next render. Sending no data keeps the logic in one place.