Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.5 — useState or useReducer?
React · Example 3 of 3

Immer inside a reducer: write mutations, get immutable state

The liked case is two short lines instead of three levels of spread and map. The old state is untouched, the changed branch is new, and the unchanged playlist is the very same object, so a memo row for it could skip rendering.

Both hold the same kind of local state; choose useState for simple, independent values and useReducer when many handlers update the same state in related ways, when you want to read and debug every change as an action, or test the logic as a plain function, and add Immer when the updates are deeply nested.

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 withLogger(reducer) wrapper that logs action.type and the next state, and use it with any reducer.

02

Write two tests (plain functions or Vitest) for a counterReducer with incremented and reset: one per action.

Explain it without notes

01

Compare useState and useReducer on code size, readability, debugging and testing.

02

When would you switch a component from useState to useReducer?

03

How do you test a reducer, and why is it easier than testing a component?

04

What is Immer, how does it work with reducers, and what are its two main rules?

Immer inside a reducer: write mutations, get immutable state

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

old likes: 0 new likes: 1
Road trip copied: true
Study shared, not copied: true
result is frozen: true