Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.4 — useReducer: State Logic in One Place
React · Example 1 of 4

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.

01

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.

02

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

01

What is a reducer, and what does useReducer return?

02

Why should actions describe what happened rather than how state changes?

03

Why must reducers be pure, and what happens if one mutates state?

04

When and why would you pass a third argument to useReducer?

05

What does dispatch do, and is its identity stable?

A counter with a reducer

Preview

Press Run to see the page.

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