Zustand is a small React state library with a hooks API. Install it, create a store, use selectors and middleware, and avoid the common mistakes.
Zustand is a small, fast state management library for React that gives you a store as a hook: create it with create, read it with a selector, and skip the providers.[1] Install it with npm install zustand.[1] The latest version on npm at the access date is 5.1.0, it ships with built-in TypeScript types and has zero dependencies, and the repository carries an MIT license.[2][3] The verdict: use it when React state has outgrown useState and prop drilling, and you want less ceremony than Redux. Five mistakes are covered below, led by selectors that return new objects, mutating state, and sharing one store across Next.js requests.
What Zustand is
The project describes itself as a "small, fast, and scalable bearbones state management solution" with an API based on hooks that is not boilerplatey or opinionated, but has "enough convention to be explicit and flux-like."[1] Its docs say a lot of effort went into common pitfalls, naming the zombie child problem, React concurrency and context loss between mixed renderers.[1]
The model is simple. The store is a hook, and it can hold primitives, objects and functions. The set function merges state into the existing state rather than replacing it.[1] Components subscribe through a selector, and a component re-renders when the selected value changes. No provider wraps the app.[1]
Install Zustand and create a store
Run npm install zustand, then use the introduction example from the docs: one store with state and actions, and two components that each select only what they need.[1]
import { create } from 'zustand'
const useBear = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
updateBears: (newBears) => set({ bears: newBears }),
}))
function BearCounter() {
const bears = useBear((state) => state.bears)
return <h1>{bears} bears around here...</h1>
}
function Controls() {
const increasePopulation = useBear((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}Notice that Controls selects an action, not state. Actions are plain functions stored beside the data, and the docs example selects each one separately from the state it updates.
Update state without mutating it
Calling set with a partial object shallowly merges it into the store.[5] That covers flat state. Nested state needs more work: the docs call the normal approach copying each level with the spread operator, and admit it is "very long."[5] The npm README states the rule directly: state has to be updated immutably.[2]
Three escape hatches exist for deep updates, all listed in the docs: Immer, optics-ts and Ramda.[5] The Immer middleware (imported from zustand/middleware/immer) lets you write mutation-style code inside set, such as state.bees += by, while the library produces an immutable update.[2] The middleware docs say you need to install the immer library separately.[6]
The README also documents a second argument to set, false by default. Pass true and the state is replaced instead of merged, so "be careful not to wipe out parts you rely on, like actions."[2]
Select state so components re-render less
Zustand compares selector output with strict equality by default, which the README calls efficient for atomic picks.[2] Two separate selectors for two values is the cheapest pattern:
const nuts = useBearStore((state) => state.nuts)const honey = useBearStore((state) => state.honey)[2]
Calling the hook with no selector works, but the README warns that the component then updates on every state change.[2] When one selector must return an object, an array or a derived value, wrap it in useShallow. The docs explain why: a computed selector causes a re-render if its output changed according to Object.is, and useShallow skips the re-render when the new output is shallow equal to the previous one.[4]
import { create } from 'zustand'
import { useShallow } from 'zustand/react/shallow'
const useMeals = create(() => ({
papaBear: 'large porridge-pot',
mamaBear: 'middle-size porridge pot',
littleBear: 'A little, small, wee pot',
}))
export const BearNames = () => {
const names = useMeals(useShallow((state) => Object.keys(state)))
return <div>{names.join(', ')}</div>
}In the docs example, useMeals.setState({ papaBear: 'a large pizza' }) re-renders the component without useShallow even though the key list is unchanged. With it, the component stays put.[4] The README shows the same wrapper for object and array picks, such as useShallow((state) => ({ nuts: state.nuts, honey: state.honey })).[2]
Use TypeScript, persist and devtools
Basic TypeScript use needs one change: write create<State>()(...) instead of create(...).[2] The README's example below also stacks two middlewares. The @redux-devtools/extension type import is required for devtools typing, and the devtools docs add that you need to install the @redux-devtools/extension library to use the middleware from zustand/middleware.[2][8]
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import type {} from '@redux-devtools/extension' // required for devtools typing
interface BearState {
bears: number
increase: (by: number) => void
}
const useBearStore = create<BearState>()(
devtools(
persist(
(set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
}),
{
name: 'bear-storage',
},
),
),
)| Middleware | Import | What it does | Options and notes from the docs |
|---|---|---|---|
persist | zustand/middleware | Keeps state across page reloads and restarts | name (required); optional storage, partialize, onRehydrateStorage, version, migrate, merge, skipHydration[7] |
devtools | zustand/middleware | Connects the store to Redux DevTools without Redux | Optional name, enabled, anonymousActionType, store, actionsDenylist; enabled defaults to true in development and false in production[8] |
immer | zustand/middleware/immer | Lets you write updates as mutations on a draft | Requires the immer package[6] |
subscribeWithSelector | zustand/middleware | Adds a selector-based subscribe signature | subscribe(selector, callback, options?: { equalityFn, fireImmediately })[2] |
Two persist details matter in production. The default storage is createJSONStorage(() => localStorage), and the getter is evaluated lazily so server rendering does not fail when localStorage is missing.[7] And partialize is a function that filters state fields before they are persisted, so you can keep fields you do not want in storage out of it.[7]
Common Zustand mistakes
1. A selector that returns a new object every time
A selector such as (state) => ({ nuts: state.nuts, honey: state.honey }) builds a new object on every call, so the Object.is check sees a change whenever any state changes.[4] Fix it with useShallow, or select each value separately.[2][4]
2. Subscribing to the whole store
const state = useBearStore() works, and re-renders the component on every state change.[2] The Next.js guide's example does this with useCounterStore((state) => state) to destructure count and both actions.[9] In a real store with more fields, select only the pieces the component renders.
3. Mutating state or wiping the store
The docs' deep-state example needs each level copied with the spread operator, because updating nested state has to be done immutably.[5] Writing a mutation such as ++state.deep.nested.obj.count directly in a plain set skips that, so copy each level or add the Immer middleware.[2][5] And set({}, true) clears the entire store, actions included.[2]
4. One global store shared across Next.js requests
The Zustand store is a global variable, also called module state. A Next.js server can handle several requests at once, so the docs say the store should be created per request and not shared.[9] Their recommendations are "no global stores" and that React Server Components should not read from or write to the store, since they cannot use hooks or context.[9] The README adds that reading or writing state outside components through getState and setState is not recommended for state in Server Components, because it can cause unexpected bugs and privacy issues for users.[2]
The documented pattern is a store factory built on createStore from zustand/vanilla, plus a client-side provider that creates the store once with useState.[9]
// src/stores/counter-store.ts
import { createStore } from 'zustand/vanilla'
export type CounterState = {
count: number
}
export type CounterActions = {
decrementCount: () => void
incrementCount: () => void
}
export type CounterStore = CounterState & CounterActions
export const defaultInitState: CounterState = {
count: 0,
}
export const createCounterStore = (initState: CounterState = defaultInitState) => {
return createStore<CounterStore>()((set) => ({
...initState,
decrementCount: () => set((state) => ({ count: state.count - 1 })),
incrementCount: () => set((state) => ({ count: state.count + 1 })),
}))
}// src/providers/counter-store-provider.tsx
'use client'
import { type ReactNode, createContext, useState, useContext } from 'react'
import { useStore } from 'zustand'
import { type CounterStore, createCounterStore } from '@/stores/counter-store'
export type CounterStoreApi = ReturnType<typeof createCounterStore>
export const CounterStoreContext = createContext<CounterStoreApi | undefined>(undefined)
export interface CounterStoreProviderProps {
children: ReactNode
}
export const CounterStoreProvider = ({ children }: CounterStoreProviderProps) => {
const [store] = useState(() => createCounterStore())
return <CounterStoreContext.Provider value={store}>{children}</CounterStoreContext.Provider>
}
export const useCounterStore = <T,>(selector: (store: CounterStore) => T): T => {
const counterStoreContext = useContext(CounterStoreContext)
if (!counterStoreContext) {
throw new Error(`useCounterStore must be used within CounterStoreProvider`)
}
return useStore(counterStoreContext, selector)
}The docs note this guide is due for an update based on a public discussion, so check the page before copying the structure into a production app.[9] Pages Router and App Router use the same pattern. In the App Router, the docs wrap {children} in the provider inside layout.tsx, and the example component that calls the hook starts with 'use client'.[9]
If you are building on a recent Next.js release, the Next.js 16.2 changes are worth reading alongside this setup.
5. Persist hydration that does not match the server
Next.js renders twice, once on the server and again on the client, and different output on each side causes hydration errors.[9] React's hydration rules, as quoted in the Zustand docs, list rendering different data on the server and the client, and browser-only API checks like typeof window !== 'undefined', among the most common causes. In the worst case, event handlers attach to the wrong elements.[10] A persisted store reads from localStorage, which exists only in the browser, so reading it during the first render can produce that mismatch (this is the post's inference, not a docs statement).
The persist docs give the tool for this: skipHydration defaults to false, and when it is true the middleware does not rehydrate on initialization. You call rehydrate yourself, which the docs describe as useful for server-side rendering apps.[7]
The call is positionStore.persist.rehydrate(). The docs delay it with setTimeout to demonstrate; in a React app, trigger it after the first client render instead. Two more persist cautions from the docs: createJSONStorage performs no runtime validation, so corrupt, stale or tampered data is cast straight to your state type, and the docs recommend a custom storage that validates with a schema library such as Zod for production.[7] Use version with migrate when the stored shape changes: per the docs, if the stored version does not match, the stored state is not used, and migrate handles the mismatch.[7] For schema validation on the TypeScript side, see the Zod validation guide.
Zustand vs Context vs Redux and other libraries
The README gives Zustand's case in short bullets. Against Context: less boilerplate, components render only on changes, and centralized, action-based state. Against Redux: simple and un-opinionated, hooks as the primary way to consume state, no context providers around the app, and transient updates that do not cause renders.[2] The docs comparison page adds the model differences below.[11]
| Library | State model | Providers needed | Render optimization |
|---|---|---|---|
| Zustand | Single store, immutable | No | Manual, with selectors[11] |
| Redux | Immutable, like Zustand | Yes, context providers | Manual, with selectors[11] |
| Valtio | Mutable | Not stated | Through property access[11] |
| Jotai | Primitive atoms composed together | Not stated | Through atom dependency[11] |
| Recoil | Atoms keyed by string | Yes, context provider | Through atom dependency[11] |
Read the table as a decision rule. Pick Zustand for a single shared store with explicit actions and no provider tree. Pick an atom library when state is naturally many small independent pieces, and Valtio when you want mutation syntax. The docs frame each as a trade-off, not a ranking.[11]
Quick reference
Install with npm install zustand. Create with create, and with create<State>()(...) in TypeScript. Select narrowly, and wrap object, array or derived selectors in useShallow from zustand/react/shallow. Update immutably, or add the Immer middleware. Persist with partialize and a version. In Next.js, create the store per request with createStore and a provider, and keep Server Components away from it.
Sources
- Introduction, Zustand Docs (accessed November 28, 2026)
- zustand, npm package page and README, version 5.1.0 (accessed November 28, 2026)
- pmndrs/zustand, GitHub repository (accessed November 28, 2026)
- Prevent rerenders with useShallow, Zustand Docs (accessed November 28, 2026)
- Updating state, Zustand Docs (accessed November 28, 2026)
- immer middleware, Zustand Docs (accessed November 28, 2026)
- persist middleware, Zustand Docs (accessed November 28, 2026)
- devtools middleware, Zustand Docs (accessed November 28, 2026)
- Setup with Next.js, Zustand Docs (accessed November 28, 2026)
- SSR and Hydration, Zustand Docs (accessed November 28, 2026)
- Comparison, Zustand Docs (accessed November 28, 2026)
Written by
WOWHOW
The WOWHOW team brings 14+ years of production engineering experience. Every tool and product in the catalog is built, tested, and curated in-house.
Monday memo · free
One insight, every Monday. 7am IST.
1 field report, 3 links, 1 tool we actually use. No fluff, no spam.
Beyond the writing
Need production-ready templates?
Free browser tools with no signup, plus premium dev templates and starter kits.
Comments · 0
Beta: comments are stored locally on your device and not visible to other readers.
No comments yet. Be the first to share your thoughts.