Chapter 2 · Practice 5 of 5
Use a reducer when several state values change together
From State and data flow
Why it matters
When one user action updates three pieces of state, or the next state depends on several current values, scattered useState calls get hard to reason about.
Move the logic into a reducer with useReducer:
- Each action describes what happened, named after the event:
added,removed,cleared. - The reducer decides the next state in one pure function.
Reducers are easy to unit test without rendering anything. Keep them pure: no requests or timers inside.
A simple sign that you need one is an event handler that calls four setters in a row.
Do
- Name actions after events:
added,removed,cleared
Avoid
- Side effects inside the reducer function