Reducers must be pure: StrictMode calls them twice
This example uses StrictMode on purpose. One click each: the impure reducer added Milk twice, because its second (StrictMode) call pushed into the same array again. The pure reducer gives the same answer however often it runs. In production the reducer runs once, so the bug would hide until something else re-runs it.
useReducer(reducer, initialState) keeps a component's state like useState, but every change goes through one pure function, reducer(state, action), that returns the next state; event handlers only dispatch actions that describe what happened.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a lightReducer for a traffic light with actions next (green → yellow → red → green) and broke (goes to "flashing"), plus repaired (back to "red"). Use it in a component with two buttons.
Convert this to useReducer: const [form, setForm] = useState({ name: "", email: "" }) with handlers setForm({ ...form, name: v }), setForm({ ...form, email: v }) and setForm({ name: "", email: "" }).
Explain it without notes
What is a reducer, and what does useReducer return?
Why should actions describe what happened rather than how state changes?
Why must reducers be pure, and what happens if one mutates state?
When and why would you pass a third argument to useReducer?
What does dispatch do, and is its identity stable?
Preview
Console
Nothing logged yet.Expected console output
Milk, Milk
Milk