When a piece of state can change in many ways (add, subtract, change the step, reset), the rules for changing it are easily scattered over many handlers. useReducer gathers all of those rules into one function called a reducer. Imagine a small restaurant. You don't walk into the kitchen and change the order yourself. You write a slip, say "add one", and give it to the cook. The cook reads the slip, checks the current order, then writes the new order following the rule book. The slip is the action, giving it to the cook is dispatch, the cook's rule book is the reducer, and the current order is the state.
Three parts: state, action, reducer
- State: the data right now, for example
{ count: 0, step: 1 }. - Action: a plain object that describes what happened. It has at least a
type, for example{ type: "increment" }. An action can carry extra data:{ type: "setStep", step: 5 }. - Reducer: a function
(state, action) => newState. A reducer takes the current state and an action, then returns the new state. dispatch(action): how a component sends an action to the reducer.
The reducer: the rule book
Here is the reducer for a counter that has a count (the number) and a step (the size of each step):
const initialState = { count: 0, step: 1 }
function reducer(state, action) {
switch (action.type) {
case "increment":
return { ...state, count: state.count + state.step }
case "decrement":
return { ...state, count: state.count - state.step }
case "setStep":
return { ...state, step: action.step }
case "reset":
return initialState
default:
return state
}
}
switch (action.type)picks the rule that matches the kind of action.- Every
casereturns a new object....statecopies the properties that don't change, then the changed property is written after it. setStepuses the data its action carries:action.step.resetreturnsinitialState, socountandstepboth go back to the start.default: return statehandles an action it doesn't know: the old state is returned as it is. So a mistyped action, for example"incremnt", causes no error and changes nothing. Because there's no error, a typo like this is easy to miss.
A reducer has to be pure: it only calculates the new state from the old state and the action. A reducer must not fetch, set timers, or change the old state object.
Using it in a component: useReducer and dispatch
This Counter component uses the reducer above:
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<div>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<input
type="range"
min="1"
max="5"
value={state.step}
onChange={(e) => dispatch({ type: "setStep", step: Number(e.target.value) })}
/>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
)
}
useReducer(reducer, initialState)takes two arguments: the reducer function and the starting state.useReducerreturns[state, dispatch]: the current state, and a function that sends actions.- The component calculates nothing. The component only sends an action that says what happened. The reducer calculates the new state, then React renders again with that state.
- In the exercise editor,
useReduceris already available with noimport. In a real project, writeimport { useReducer } from "react".
This is what the Lab's console records when you send these actions one by one, in this order:
| Action sent | State before | State after | Shown |
|---|---|---|---|
{ type: "increment" } |
{ count: 0, step: 1 } |
{ count: 1, step: 1 } |
1 |
{ type: "increment" } |
{ count: 1, step: 1 } |
{ count: 2, step: 1 } |
2 |
{ type: "setStep", step: 5 } |
{ count: 2, step: 1 } |
{ count: 2, step: 5 } |
2 |
{ type: "increment" } |
{ count: 2, step: 5 } |
{ count: 7, step: 5 } |
7 |
{ type: "incremnt" } |
{ count: 7, step: 5 } |
{ count: 7, step: 5 }, the same |
7 |
{ type: "reset" } |
{ count: 7, step: 5 } |
{ count: 0, step: 1 } |
0 |
When to use useReducer instead of useState
useStatefor a value that stands on its own with simple changes: an open/close switch, one input field, a counter that adds one.useReducerfor complex state with many kinds of action, or several values that change together: a shopping cart (add, remove, change the amount, empty it), a multi-step form (next, back, start again).- All the rules live in one plain function, so a reducer is easy to test without rendering anything:
reducer({ count: 2, step: 5 }, { type: "increment" })is always{ count: 7, step: 5 }. The action history can be recorded too, like the Lab's console. - State libraries such as Redux use the same action and reducer pattern. Using
useReducertogether with Context is covered again in the State Management lesson.
⚠️ Reducers that quietly break the state
- Changing the old state.
state.count++thenreturn statereturns the same object. React compares the old and new state withObject.is(similar to===). Because the object is the same, React decides nothing changed, and the screen doesn't update. Always return a new object. - Forgetting
default. Withoutdefault: return state, an unknown action makes the reducer returnundefined, andstate.countcrashes right away. - Forgetting
...state. In a reducer that also hasstep,return { count: state.count + 1 }removesstepfrom the state. - Side effects in the reducer. Put fetching, timers or
localStoragein an event handler oruseEffect. In development with StrictMode, React calls the reducer twice, so that a reducer that isn't pure is found quickly.
TL;DR: useReducer gathers all the rules for changing a state into one function, the reducer. useReducer(reducer, initialState) takes two arguments, the reducer function and the starting state, and returns [state, dispatch]. A component sends actions (objects that say what happened) with dispatch({ type: "increment" }), and an action can carry data ({ type: "setStep", step: 5 }). The reducer is a function (state, action) => newState that picks the rule with a switch (action.type). It has to be pure: it only calculates, with no side effects. Every case returns a new object ({ ...state, count: ... }), and default: return state makes a mistyped action change nothing. Use useReducer for complex state with many kinds of action. For simple values, useState is enough.
⚡ The reducer: the rule book
Write:
const initialState = { count: 0, step: 1 }
function reducer(state, action) {
switch (action.type) {
case "increment":
return { ...state, count: state.count + state.step }
case "reset":
return initialState
default:
return state
}
}
Meaning: A reducer is a function that takes the current state and an action (an object that says what happened, for example { type: "increment" }). The reducer then returns a new state. switch (action.type) picks the rule, and ...state copies the parts that don't change. An unknown action goes to default, and the state is returned as it is.
⚡ useReducer and dispatch
Write:
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<div>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</div>
)
}
Guess first: useReducer takes two arguments. What are they?
The reducer function and the starting state. It returns [state, dispatch].
Meaning: The component doesn't change the state itself. The component only sends actions through dispatch, then the reducer calculates the new state, and React renders again.
⚡ When to use useReducer
Meaning: useState for a value that stands on its own with simple changes. useReducer for complex state with many kinds of action, or several values that change together, such as a shopping cart (add, remove, change the amount, empty it).