Zustand: Lightweight State Management for React
You put the logged-in user, the theme and the cart into a React Context because it was the quickest way to share them. A few weeks later, typing in a search box re-renders half the app, because every consumer of that context updates whenever any value in it changes. The usual next step is Redux, and suddenly a "toggle sidebar" feature needs an action, a reducer, a selector and a Provider.
Zustand (German for "state") sits in between. It's a very small library from the pmndrs collective (the people behind React Spring and React Three Fiber) that gives you a global store as a hook, with almost no setup. This post covers creating stores, async actions, selectors, the persist and devtools middleware, TypeScript, and a shopping cart example, plus the spots where I think Zustand is the wrong tool.
The core is around 1KB gzipped, noticeably smaller than Redux Toolkit plus react-redux. There's no Provider to wrap your app in, no action types or reducers, and components that use a selector only re-render when the value they selected changes.
How Zustand Works
The whole API fits in your head: you call create() to define a store, and you get back a hook you can call in any component that needs the state. That's most of it.
A few design choices are what make it pleasant to use day to day:
- No Provider required: Unlike Context API or Redux, you don't need to wrap your component tree in a
<Provider>. Stores are module-level singletons. - Selector-based subscriptions: Components only re-render when the specific slice of state they subscribe to changes, not every time anything in the store changes.
- Actions live in the store: You define both state and state-modifying functions in one place, making your logic self-contained and easy to test.
- Works outside React: Because stores are plain JavaScript objects, you can read and update state from non-React code (utilities, event handlers, etc.).
- Middleware ecosystem: Persistence, DevTools, immer integration, and more are available as composable middleware.
Zustand's subscription model: components subscribe to slices of state independently
Installation and Setup
Setup is one install command and no config. Zustand ships its own TypeScript types. Version 4 works with any hooks-era React (16.8+); version 5 needs React 18 or newer, so check which one you're pulling in on an older project.
Install Zustand
Add it with npm, yarn, or pnpm. React is the only peer dependency.
# npm
npm install zustand
# yarn
yarn add zustand
# pnpm
pnpm add zustand
Create Your First Store
A store file can live anywhere. Most projects use src/store/ or src/stores/.
Use the Store in Components
Import the store hook and call it in any component. No Provider needed.
Creating Your First Store
You pass create a callback. It receives a set function for updating state and returns one object that holds both your state and your actions.
import { create } from 'zustand'
const useCounterStore = create((set) => ({
// State
count: 0,
// Actions
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
incrementBy: (amount) => set((state) => ({ count: state.count + amount })),
}))
export default useCounterStore
Actions sit right next to the state they change. There are no action creators and no reducer switch statements. The set function can accept either an object (partial state merge) or a function that receives the current state and returns the new state.
Using the Store in Components
import useCounterStore from '../store/counterStore'
function Counter() {
// Subscribe to the entire store
const { count, increment, decrement, reset } = useCounterStore()
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
)
}
// Another component that only reads the count
function CountDisplay() {
// Use a selector to subscribe only to 'count'
// This component only re-renders when count changes
const count = useCounterStore((state) => state.count)
return <p>Current count: {count}</p>
}
Pass a selector when you read from a store: useStore(state => state.count). Without one, the component re-renders whenever any part of the store changes. With one, it only re-renders when that value changes. The Counter above gets away with no selector because the store is tiny, but I wouldn't do it in a real store.
Advanced State Patterns
Async Actions and Data Fetching
There's no thunk or saga layer here. Actions are plain functions, so you mark them async and call set whenever you like: before the request, after it, or in the catch.
import { create } from 'zustand'
const useUserStore = create((set, get) => ({
users: [],
loading: false,
error: null,
selectedUser: null,
fetchUsers: async () => {
set({ loading: true, error: null })
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await res.json()
set({ users, loading: false })
} catch (error) {
set({ error: error.message, loading: false })
}
},
selectUser: (id) => {
const user = get().users.find((u) => u.id === id)
set({ selectedUser: user })
},
clearSelected: () => set({ selectedUser: null }),
}))
export default useUserStore
The second argument, get, returns the current state from inside an action. You need it whenever an action has to read something before it writes, like selectUser does.
import { useEffect } from 'react'
import useUserStore from '../store/userStore'
function UserList() {
const users = useUserStore((s) => s.users)
const loading = useUserStore((s) => s.loading)
const error = useUserStore((s) => s.error)
const fetchUsers = useUserStore((s) => s.fetchUsers)
const selectUser = useUserStore((s) => s.selectUser)
useEffect(() => {
fetchUsers()
}, [fetchUsers])
if (loading) return <div>Loading users...</div>
if (error) return <div>Error: {error}</div>
return (
<ul>
{users.map((user) => (
<li key={user.id} onClick={() => selectUser(user.id)}>
{user.name} - {user.email}
</li>
))}
</ul>
)
}
Derived State with Selectors
Selectors can compute derived values on the fly. If a selector returns a new object or array, wrap it in useShallow so Zustand compares the fields by value instead of by reference. For computations that are actually expensive, select the raw data and do the work in useMemo, because the selector runs on every store update.
In Zustand v5, a selector like useStore(s => ({ a: s.a, b: s.b })) without useShallow returns a fresh object every time, and React throws "Maximum update depth exceeded", usually with a console warning that "The result of getSnapshot should be cached". In v4 the same code just re-rendered too often. If you see either message after upgrading, look for selectors that build objects, arrays, or call .filter()/.map().
import { useShallow } from 'zustand/react/shallow'
import useCartStore from '../store/cartStore'
function CartSummary() {
// useShallow prevents re-renders when object identity changes
// but values are the same
const { itemCount, totalPrice } = useCartStore(
useShallow((state) => ({
itemCount: state.items.reduce((sum, item) => sum + item.qty, 0),
totalPrice: state.items.reduce(
(sum, item) => sum + item.price * item.qty,
0
),
}))
)
return (
<div>
<p>{itemCount} items, ${totalPrice.toFixed(2)}</p>
</div>
)
}
Middleware: Persistence and DevTools
Middleware in Zustand is just a function that wraps your store creator, so you can stack them. The two I reach for most are persist (saves state to localStorage or sessionStorage) and devtools (connects the store to the Redux DevTools browser extension).
Persist Middleware
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
const useSettingsStore = create(
persist(
(set) => ({
theme: 'dark',
language: 'en',
notifications: true,
setTheme: (theme) => set({ theme }),
setLanguage: (language) => set({ language }),
toggleNotifications: () =>
set((state) => ({ notifications: !state.notifications })),
}),
{
name: 'app-settings', // localStorage key
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({ // only persist these fields
theme: state.theme,
language: state.language,
}),
}
)
)
export default useSettingsStore
Without partialize, every non-function field gets written to storage, including things like loading flags or error messages you don't want to restore on the next visit. (Functions are simply dropped by JSON.stringify.) The bigger trap is server rendering: in Next.js the server has no localStorage, so the first client render uses the defaults and then jumps to the stored values, which can cause hydration mismatch warnings. Render persisted values only after mount, or use the skipHydration option and call rehydrate() yourself. If you change the shape of persisted state later, bump version and add a migrate function, otherwise users keep loading the old shape.
DevTools Middleware
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
const useTodoStore = create(
devtools(
(set) => ({
todos: [],
filter: 'all',
addTodo: (text) =>
set(
(state) => ({ todos: [...state.todos, { id: Date.now(), text, done: false }] }),
false, // false = merge (not replace)
'todos/addTodo' // action name shown in DevTools
),
toggleTodo: (id) =>
set(
(state) => ({
todos: state.todos.map((t) =>
t.id === id ? { ...t, done: !t.done } : t
),
}),
false,
'todos/toggleTodo'
),
removeTodo: (id) =>
set(
(state) => ({ todos: state.todos.filter((t) => t.id !== id) }),
false,
'todos/removeTodo'
),
setFilter: (filter) => set({ filter }, false, 'todos/setFilter'),
}),
{ name: 'TodoStore' }
)
)
export default useTodoStore
Combining Middleware
You can stack persist, devtools, and immer. Put devtools on the outside so it sees every change, which gives you devtools(persist(immer(...))). The immer middleware needs the immer package installed separately.
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
const useStore = create(
devtools(
persist(
immer((set) => ({
items: [],
addItem: (item) =>
set((state) => {
// With immer, mutate directly!
state.items.push(item)
}),
removeItem: (id) =>
set((state) => {
state.items = state.items.filter((i) => i.id !== id)
}),
})),
{ name: 'my-store' }
),
{ name: 'MyStore' }
)
)
TypeScript Integration
The types work well once you know the pattern: write an interface for the store and pass it as a generic to create.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface CartItem {
id: number
name: string
price: number
qty: number
}
interface CartState {
items: CartItem[]
addItem: (item: Omit<CartItem, 'qty'>) => void
removeItem: (id: number) => void
updateQty: (id: number, qty: number) => void
clearCart: () => void
totalPrice: () => number
}
const useCartStore = create<CartState>()(
persist(
(set, get) => ({
items: [],
addItem: (item) =>
set((state) => {
const existing = state.items.find((i) => i.id === item.id)
if (existing) {
return {
items: state.items.map((i) =>
i.id === item.id ? { ...i, qty: i.qty + 1 } : i
),
}
}
return { items: [...state.items, { ...item, qty: 1 }] }
}),
removeItem: (id) =>
set((state) => ({
items: state.items.filter((i) => i.id !== id),
})),
updateQty: (id, qty) =>
set((state) => ({
items: qty === 0
? state.items.filter((i) => i.id !== id)
: state.items.map((i) => (i.id === id ? { ...i, qty } : i)),
})),
clearCart: () => set({ items: [] }),
totalPrice: () =>
get().items.reduce((sum, item) => sum + item.price * item.qty, 0),
}),
{
name: 'shopping-cart',
partialize: (state) => ({ items: state.items }),
}
)
)
export default useCartStore
export type { CartItem, CartState }
Watch the extra ()(): create<State>()(persist(...)). TypeScript can't take one generic from you and infer the rest in the same call, so Zustand splits it into two calls. Forget the empty parentheses and you get confusing type errors about the middleware, not about your state.
Real-World Example: Shopping Cart
Here's the cart store from above wired into three components. Each one selects only what it needs:
function ProductCard({ product }) {
const addItem = useCartStore((s) => s.addItem)
return (
<div className="product-card">
<h3>{product.name}</h3>
<p>${product.price.toFixed(2)}</p>
<button onClick={() => addItem(product)}>
Add to Cart
</button>
</div>
)
}
// This component ONLY re-renders when item count changes
// Even if prices update, it stays quiet
function CartBadge() {
const itemCount = useCartStore(
(s) => s.items.reduce((sum, item) => sum + item.qty, 0)
)
if (itemCount === 0) return null
return (
<span className="badge">
{itemCount}
</span>
)
}
Zustand vs. Other State Libraries
The right pick depends on the app and the team. This is roughly how they compare:
| Feature | Zustand | Redux Toolkit | Context API | Jotai |
|---|---|---|---|---|
| Bundle size | ~1KB | Several times larger (with react-redux) | Built-in | ~3KB |
| Boilerplate | Minimal | Moderate | Low | Minimal |
| Provider needed | No | Yes | Yes | Optional |
| DevTools | Via middleware | Built-in | No | Via Jotai DevTools |
| Async support | Native (just async fn) | createAsyncThunk | Manual | Async atoms |
| Re-render optimization | Selectors | useSelector | Poor (whole tree) | Atom-level |
| Works outside React | Yes | Yes | No | No |
| Learning curve | Very low | Moderate | Low | Low |
| Best for | Most apps | Complex enterprise apps | Simple/low-frequency state | Atomic, fine-grained state |
My default for client-side global state is Zustand. I'd pick Redux Toolkit when a large team benefits from its enforced structure, or when you want RTK Query in the same package. Context is fine for values that rarely change (theme, locale, the current user), but not for state that updates often, because every consumer re-renders.
Zustand Patterns Quick Reference
| Pattern | Code |
|---|---|
| Read entire store | const state = useStore() |
| Read one field | const count = useStore(s => s.count) |
| Read multiple fields | const {a, b} = useStore(useShallow(s => ({a: s.a, b: s.b}))) |
| Update state (merge) | set({ count: 5 }) |
| Update state (functional) | set(s => ({ count: s.count + 1 })) |
| Replace state (not merge) | set({ count: 0 }, true) |
| Read state in action | const value = get().someField |
| Access store outside React | useStore.getState().someAction() |
| Subscribe outside React | useStore.subscribe(listener) |
| Reset store | set(initialState, true) |
When I'd Use Zustand (and When I Wouldn't)
Zustand is good at one job: client state that several unrelated parts of the app need to share. That's where I use it:
Good Fits
- UI and session state shared across the tree: sidebar open/closed, the current user, a cart, toast notifications.
- State that non-React code has to touch: a WebSocket handler or an axios interceptor can call
useStore.getState()orsetState()directly. - Small persisted preferences: theme, language, a draft form, with
partializekeeping the stored payload small. - Frequently updating values: a selector keeps re-renders limited to the components that read the changed field.
And here's where I'd skip it or limit what goes into it:
- Server data: the
fetchUsersstore above is fine for a demo, but in a real app caching, refetching, deduping and invalidation are what TanStack Query (or RTK Query, or SWR) do. Keeping API responses in Zustand means writing all of that yourself. I keep Zustand for client state and let a query library own server state. - State that belongs to one component or one form:
useStateor a form library is simpler, and it gets cleaned up when the component unmounts. - Server rendering with per-request data: a module-level store is shared by every request on a Node server, so one user's data can end up in another user's render. In Next.js App Router, create the store per request and pass it down through a Context, as the Zustand docs describe.
- Large teams that want strict conventions: Zustand doesn't enforce any structure. Without agreed rules, you end up with one giant store and actions spread across every file. Redux Toolkit's opinions can be worth the extra code there.
One more habit that saves pain in tests: stores are singletons, so state leaks from one test to the next. Export an initial state object and call useStore.setState(initialState, true) in beforeEach.
Start with one store per feature, keep server data out of it, and use selectors everywhere. That covers most of what goes wrong with Zustand in practice.