A counter with a reducer
The script clicks +, +, Step 5, +, Reset. Every button only dispatches an action; how the numbers change is decided in one place, counterReducer.
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
render: count 0 step 1
render: count 1 step 1
render: count 2 step 1
render: count 2 step 5
render: count 7 step 5
render: count 0 step 5