Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.3 — Zustand
React · Example 1 of 3

A Zustand store: selectors decide who re-renders

No provider anywhere. Each click re-renders only the component whose selected value changed: CountLabel for count, StepPicker for step. IncrementButton selects an action, which never changes, so it renders once.

Zustand is a tiny external store library: create makes a hook that holds state and actions together, components read slices with selectors and re-render only when their slice changes, and middleware adds saving to localStorage and Redux DevTools.

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 Zustand useTodos store with todos, add(text) and toggle(id), and a component that shows how many todos are done, re-rendering only when that number changes.

02

Add persist to useTodos so the list survives reloads under the key todos, saving only the todos array.

Explain it without notes

01

How does Zustand decide which components re-render after a set?

02

What is the difference between set(partial), set(fn) and set(state, true)?

03

Why does Zustand 5 need useShallow for selectors that return objects?

04

How would you use a Zustand store safely with server rendering in Next.js?

A Zustand store: selectors decide who re-renders

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

  render CountLabel
  render StepPicker
  render IncrementButton
click Add step
  render CountLabel
click step 5
  render StepPicker
click Add step
  render CountLabel
  get() inside an action: 6