Command Palette

Search for a command to run...

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

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.

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?

Reducers must be pure: StrictMode calls them twice

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Milk, Milk
Milk