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.
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.
Add persist to useTodos so the list survives reloads under the key todos, saving only the todos array.
Explain it without notes
How does Zustand decide which components re-render after a set?
What is the difference between set(partial), set(fn) and set(state, true)?
Why does Zustand 5 need useShallow for selectors that return objects?
How would you use a Zustand store safely with server rendering in Next.js?
Preview
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}