ReactEasy
What is Zustand?
Zustand is a small, hook-based state management library from the pmndrs collective. You create a store with create((set, get) => ({ ...state, ...actions })) and use it as a hook with a selector, useStore((s) => s.count), so components re-render only when the selected value changes. It needs no provider and very little boilerplate.
Why teams like it
- Tiny API:
create,set,get, selectors. - No provider required (though you can scope stores with context).
- Selective re-renders: components subscribe to slices.
- Works outside React:
useStore.getState()anduseStore.setState()in plain functions, tests or event handlers. - Middleware:
persist(localStorage and other storage),devtools(Redux DevTools),immer,subscribeWithSelector. - TypeScript-friendly.
Version 5 notes
- Requires React 18+ and uses React's
useSyncExternalStore. - Named exports only (no default export).
- Selectors that return new objects or arrays each call can cause "Maximum update depth exceeded"; wrap them with
useShallow(fromzustand/react/shallow) or select primitives. - Equality-function variants live in
zustand/traditional.
When to choose it
Client-side global state (cart, UI preferences, editor state) in small to large apps that do not need Redux's structure. Server data still belongs in TanStack Query or similar.
Code example
tsx
1import { create } from "zustand";2import { persist } from "zustand/middleware";3import { useShallow } from "zustand/react/shallow";45type Prefs = {6 theme: "light" | "dark";7 fontSize: number;8 toggleTheme: () => void;9 setFontSize: (n: number) => void;10};1112export const usePrefs = create<Prefs>()(13 persist(14 (set) => ({15 theme: "light",16 fontSize: 16,17 toggleTheme: () => set((s) => ({ theme: s.theme === "light" ? "dark" : "light" })),18 setFontSize: (fontSize) => set({ fontSize }),19 }),20 { name: "prefs" } // saved to localStorage21 )22);2324export function ThemeButton() {25 const theme = usePrefs((s) => s.theme); // re-renders only when theme changes26 const toggle = usePrefs((s) => s.toggleTheme);27 return <button onClick={toggle}>Theme: {theme}</button>;28}2930export function FontInfo() {31 // Selecting several values: useShallow avoids re-renders for equal objects32 const { fontSize, setFontSize } = usePrefs(useShallow((s) => ({ fontSize: s.fontSize, setFontSize: s.setFontSize })));33 return <input type="range" min={12} max={24} value={fontSize} onChange={(e) => setFontSize(+e.target.value)} />;34}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.