Lazy initialisation: pass the init function, not its result
Both lists start the same, but after the clicks only the eager one runs createInitialTodos again (and throws the result away). For three items it doesn't matter; for parsing a big saved document it does.
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
createInitialTodos ran for eager
createInitialTodos ran for lazy
--- click both buttons
createInitialTodos ran for eager