TL;DR: Zustand is minimal global state for React. Define a store with
create(), use it anywhere with a hook - no Provider, no boilerplate. Subscribe to only the slices you need to avoid unnecessary re-renders. ~1kB. Official docs: zustand-demo.pmnd.rs.
What is Zustand?
Zustand is a minimal global state manager for React. You define a store - a plain object with state and actions - and subscribe to it in any component with a hook. No Provider required, no boilerplate, no reducers.
At ~1kB gzipped, it's hard to justify anything heavier for client state management.
I moved a mid-size dashboard off Redux Toolkit to Zustand a while back, mostly out of curiosity about how much boilerplate would actually disappear. The store file went from 340 lines of actions, reducers, and selectors to about 60 lines of plain functions. Nobody on the team missed the action-type constants.
When to use it
Use Zustand for client-side global state that multiple components need to share:
- Authentication state (user, token)
- UI state (sidebar open, theme, modal queues)
- Multi-step wizard state shared across routes
- Shopping cart, notification queue
Don't use it for server state (API responses) - that's TanStack Query's job. Don't use it for local component state - that's useState.
Zustand vs Jotai: Zustand is store-first (one object per domain); Jotai is atom-first (one hook per value). Zustand is easier to reason about for most teams.
Key Features
- No Provider - stores work outside React tree, usable in vanilla JS too
- Immer integration -
immermiddleware for mutation-style updates - Redux DevTools - inspect state history in browser devtools
- Persist middleware - sync state to
localStorageorsessionStorage - Subscriptions - subscribe to store changes outside React
Installation
npm install zustand
Basic Usage
import { create } from 'zustand'
interface CartStore {
items: CartItem[]
addItem: (item: CartItem) => void
removeItem: (id: string) => void
clear: () => void
}
const useCartStore = create<CartStore>((set) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
removeItem: (id) => set((state) => ({ items: state.items.filter(i => i.id !== id) })),
clear: () => set({ items: [] }),
}))
// In any component:
function CartCount() {
const count = useCartStore((state) => state.items.length)
return <span>{count}</span>
}
Using Immer for Complex Updates
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
const useStore = create<State>()(immer((set) => ({
users: [],
updateUser: (id, patch) => set((state) => {
const user = state.users.find(u => u.id === id)
if (user) Object.assign(user, patch) // Immer lets you mutate directly
}),
})))
Persist State to localStorage
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
const useSettingsStore = create<Settings>()(
persist(
(set) => ({
theme: 'light',
setTheme: (theme) => set({ theme }),
}),
{ name: 'app-settings' } // localStorage key
)
)
Subscribing Outside React
Sometimes you need to react to a state change without a component in the picture, an analytics call, a WebSocket reconnect, a toast triggered from a non-React module. subscribe handles that without turning the store into an event emitter you have to wire up yourself:
import { useCartStore } from './cart-store'
const unsubscribe = useCartStore.subscribe((state, prevState) => {
if (state.items.length > prevState.items.length) {
trackEvent('cart_item_added', { total: state.items.length })
}
})
// later, e.g. on unmount or route change
unsubscribe()
This runs outside the React render cycle entirely, so it's safe to call inside useEffect cleanup, a route change handler, or a plain script that never touches JSX.
TypeScript Tips
Always type your store interface separately - it enables reuse:
interface AuthStore {
user: User | null
token: string | null
login: (user: User, token: string) => void
logout: () => void
}
const useAuthStore = create<AuthStore>()((set) => ({
user: null,
token: null,
login: (user, token) => set({ user, token }),
logout: () => set({ user: null, token: null }),
}))
Always select only what you need - subscribing to the whole store re-renders on every change:
// ✅ Re-renders only when user.name changes
const name = useAuthStore((s) => s.user?.name)
// ❌ Re-renders on every store mutation
const store = useAuthStore()
Common Gotchas
- Object slices - if you select an object (
s => s.filters), Zustand uses reference equality. In v5 wrap the selector inuseShallowfromzustand/react/shallowto skip re-renders when the contents are equal but the reference is new. Older guides passshallowas a second argument; that is v4 and v5 ignores it (see the measurements below) - Async actions - you can call
setfrom inside async functions directly; no special middleware needed - Testing - reset store state between tests with
useStore.setState(initialState)inbeforeEach
Selectors, measured
Most Zustand advice about re-renders is stated, not counted. I rendered four components against one store with react-dom 19.3.1 and jsdom, using Zustand 5.0.15 on Node 22, and counted renders. Every component only cares about count or filters. The store then changes an unrelated field (name) ten times, and after that replaces filters ten times with a new object holding the same content.
| Selector | Initial | After 10 unrelated changes | After 10 equal-content replacements |
|---|---|---|---|
useStore() (whole store) | 1 | 11 | 21 |
useStore(s => s.count) | 1 | 1 | 1 |
useStore(s => s.filters) | 1 | 1 | 11 |
useStore(useShallow(s => s.filters)) | 1 | 1 | 1 |
Two things stand out. Selecting the whole store costs a render per change, which is the advice you already know. The less obvious row is the third: an object selector is safe against unrelated changes, but one set({ filters: { ... } }) that rebuilds the same data re-renders it every time. That's the case useShallow exists for.
The v4 shallow argument is gone
Plenty of tutorials write useStore(selector, shallow). In v5 the hook is useStore(selector) and the second argument isn't read. I checked the source of zustand/react in 5.0.15 and it takes only a selector. The measured effect is worse than "no effect": a selector that builds an object literal fails outright.
// Zustand 5: this loops
const { count, name } = useStore((s) => ({ count: s.count, name: s.name }))
// Zustand 5: this works
import { useShallow } from 'zustand/react/shallow'
const { count, name } = useStore(useShallow((s) => ({ count: s.count, name: s.name })))
The first form logged "The result of getSnapshot should be cached to avoid an infinite loop" and then threw Maximum update depth exceeded. Passing Object.is as a second argument changed nothing, the same error came back. Inside useShallow the component rendered once. If you're upgrading from v4 and still need a custom equality function on the hook, createWithEqualityFn from zustand/traditional is the route the package keeps for it (I didn't measure that one).
Two more defaults worth knowing
persist doesn't write anything when the store is created. In the run above the storage key was absent right after create, and the first set wrote {"state":{"theme":"dark"},"version":0}, with partialize keeping the token field out. So a user who never changes a setting has nothing stored, and your code should treat a missing key as normal.
setState merges only the top level. After setState({ nested: { x: 9 } }) on a store whose nested was { x: 1, y: 2 }, the value was { x: 9 } and y was gone. Passing true as the second argument replaced the whole state, dropping every key not supplied.
What this run does not cover
The counts come from jsdom and React 19 in development mode, with a store that holds a handful of fields. I didn't measure render time, so a re-render counted here may be cheap or expensive in your tree. The persist check used a synchronous in-memory storage, so I can't tell you how an async storage behaves while it hydrates. To reproduce the counts, install zustand@5.0.15, react@19, react-dom@19 and jsdom, render the four components inside act() from react, and bump a counter in each component body.
When Not to Reach for It
Zustand is small enough that people install it reflexively, which is how a project ends up with a global store holding data that never needed to be global. Two cases where something else is the better answer.
State that belongs to one component subtree. If a value is read by a form and its three children and nothing else, useState plus prop passing, or a context if the tree is deep, keeps the data where it lives. A store makes it reachable from everywhere, which sounds like flexibility until you're tracing which of eleven files mutated a flag.
Server data. Cached API responses need invalidation, refetch on focus, retry, and a notion of staleness. Putting them in Zustand means writing all of that yourself, badly. Pair it with TanStack Query instead and let each tool hold the kind of state it's built for: server cache in the query client, client UI state in the store. Teams that skip this split spend their time keeping two copies of the same record in sync.
The honest summary is that Zustand is excellent at domain stores and unremarkable at everything else, which is fine, because that's what it set out to be.
Related
- Jotai - atom-based alternative to Zustand; better for fine-grained subscriptions, Zustand is better for domain stores
- TanStack Query - use alongside Zustand: TanStack Query for server/async state, Zustand for client UI state
- TypeScript Generics Guide - type your Zustand stores with generic interfaces for full
create<StoreType>()safety