Reducers and Complex State Transitions
Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.
What you will be able to do
#- Model interrelated state with a pure reducer.
- Use lazy initialization for expensive initial state.
- Test a reducer as a plain function.
Overview
#When state has many transitions
useState is fine for one or two independent values. When several values change together, or the next state depends on the current state in many ways, a reducer centralizes the logic. The reducer is a pure function (state, action) => state, which makes every transition explicit and testable.
type State = { items: Item[]; filter: string };
type Action =
| { type: 'add'; item: Item }
| { type: 'remove'; id: string }
| { type: 'filter'; value: string };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'add': return { ...state, items: [...state.items, action.item] };
case 'remove': return { ...state, items: state.items.filter((i) => i.id !== action.id) };
case 'filter': return { ...state, filter: action.value };
}
}
Lazy initialization
If the initial state is expensive to compute, pass an initializer function as the third argument so it runs once.
const [state, dispatch] = useReducer(reducer, props, createInitialState);
Reducers must be pure
No mutation, no side effects, no random values, no Date.now inside the reducer. Return new state. Side effects belong in the action creator or an effect.
Reducer with context
Pair a reducer with context to give distant components a dispatch function without prop drilling. Split value and dispatch into separate contexts so dispatch-only consumers do not re-render.
Testing a reducer
A reducer is a plain function, so you test it directly: given a state and an action, assert the next state. No rendering required.
Pitfall: dispatching during render
Dispatch is for event handlers and effects, not render. Calling dispatch during render schedules an update that can loop. Use it in handlers or in an effect with correct dependencies.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What is the next state after dispatching increment twice from count 0?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.tsxfunction reducer(state: { count: number }, action: { type: 'inc' }) { return { count: state.count + 1 }; } dispatch({ type: 'inc' }); dispatch({ type: 'inc' });Exercise 2Implement
Implement a reducer for a todo list supporting add, toggle and remove, and wire it with useReducer.
starter.tsxtype Todo = { id: string; text: string; done: boolean }; type State = { todos: Todo[] }; type Action = | { type: 'add'; todo: Todo } | { type: 'toggle'; id: string } | { type: 'remove'; id: string };Reveal the reference answer
reference.tsxtype Todo = { id: string; text: string; done: boolean }; type State = { todos: Todo[] }; type Action = | { type: 'add'; todo: Todo } | { type: 'toggle'; id: string } | { type: 'remove'; id: string }; function reducer(state: State, action: Action): State { switch (action.type) { case 'add': return { todos: [...state.todos, action.todo] }; case 'toggle': return { todos: state.todos.map((t) => t.id === action.id ? { ...t, done: !t.done } : t) }; case 'remove': return { todos: state.todos.filter((t) => t.id !== action.id) }; } } function TodoApp() { const [state, dispatch] = useReducer(reducer, { todos: [] }); return <ul>{state.todos.map((t) => <li key={t.id} onClick={() => dispatch({ type: 'toggle', id: t.id })}>{t.text}</li>)}</ul>; }Authored expected output: Dispatching add, toggle and remove updates the list immutably.
Each branch returns a new state object with the relevant change, keeping the reducer pure. The component dispatches plain action objects.
Exercise 3Debug
This reducer does not update the UI. Explain and fix.
starter.tsxfunction reducer(state: State, action: Action) { if (action.type === 'add') { state.items.push(action.item); } return state; }Reveal the reference answer
reference.tsxfunction reducer(state: State, action: Action) { if (action.type === 'add') { return { ...state, items: [...state.items, action.item] }; } return state; }Authored expected output: The list updates when an item is added.
The reducer mutates the array and returns the same state reference, so React sees no change and skips the update. Returning a new object with a new array gives React a new reference.
Exercise 4Explain
Explain when a reducer is a better fit than several useState calls.
starter.tsx// many interdependent values vs one reducerReveal the reference answer
reference.tsxA reducer fits when several pieces of state change together, when the next state depends on the previous state in many ways, or when the transitions are complex enough that spreading them across event handlers becomes error-prone. It centralizes the logic in one pure function that is easy to read and test, and it pairs naturally with context for distant components. useState is simpler for one or two independent values, so a reducer is not automatically better.Authored expected output: A written rule based on interrelated state, transition complexity and testability.
The deciding factors are how many values change together and how complex the transitions are. Reducers trade a little ceremony for a single, testable source of transitions.
Common misconceptions
#- Reducers may mutate state. They must be pure and return new state.
- useReducer is always better than useState. Use a reducer when transitions are complex or state is interrelated.
- Side effects belong in the reducer. Keep the reducer pure; put effects elsewhere.
- A reducer cannot be tested without rendering. It is a plain function and is tested directly.
Follow-up practice
#- react-context-performance
- react-component-architecture
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.