Command Palette

Search for a command to run...

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

persist middleware and using the store outside React

The store starts as dark because persist loaded the saved JSON when the store was created (localStorage loads synchronously). partialize keeps menuOpen out of storage. The preview's localStorage is in memory and resets on every Run; in a real browser the theme would survive a reload.

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?

persist middleware and using the store outside React

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

loaded theme: dark
analytics: theme -> light
saved: {"state":{"theme":"light","fontSize":18},"version":0}
saved: {"state":{"theme":"light","fontSize":20},"version":0}