Home / Learn React / useReducer: Complex State
useReducer: Complex State
When state has many related pieces and many ways to change, put the update logic in a reducer function: given the old state and an action, return the new state.
Theory in plain words
What it is
A reducer is a pure function (state, action) => newState. useReducer keeps the state and gives you dispatch to send actions to the reducer.
Why we use it
When many event handlers each change the same state in slightly different ways, the logic is scattered. A reducer puts every possible change in one place, which is easy to read, test and debug.
How it works
You call dispatch(action). React calls your reducer with the current state and that action, takes the returned value as the new state and renders. Never mutate state inside the reducer.
Where it is used
- Todo lists, carts and wizards with many actions
- Forms with many related fields
- Together with Context for app wide state
- State machines (loading, success, error)
A cart with a reducer
| useState | useReducer | |
|---|---|---|
| Best for | Simple, independent values | Many related values and many kinds of changes |
| Update logic | Inside event handlers | In one reducer function |
| Testing | Test the component | Test the reducer alone, it is a pure function |
| Code size | Less at first | More at first, less as it grows |
Quick quiz
1. What does a reducer return?
(state, action) returns the new state.
2. What does dispatch do?
React then calls the reducer with it.
3. When is useReducer better than useState?
It centralizes update logic.
Common questions
What does a reducer return?
The new state. (state, action) returns the new state.
What does dispatch do?
Sends an action to the reducer. React then calls the reducer with it.
When is useReducer better than useState?
For many related values and many kinds of updates. It centralizes update logic.