Sub topic 10
How middleware wraps a store
This chapter assumes you can create a store with create, update it with set, and type it with the create<T>()(...) form from earlier chapters. It explains what middleware is, how it composes, and what goes wrong when you stack it. The specific middleware (persist, devtools, immer) get their own chapters. Here we focus on the mechanism they share.
What middleware is
Middleware is a function that takes a state creator and returns a new state creator. A state creator is the function you pass to create. It receives set, get and the store API, and returns the initial state and actions.
Because the input and output have the same shape, create cannot tell whether it received your plain creator or one that was wrapped. The wrapper can change what set does, read the state after each update, or fill in the initial state before your creator runs.
import { create } from 'zustand'
interface CounterState {
count: number
increment: () => void
}
// Plain state creator
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))The arrow function above is the state creator. Every middleware in this chapter wraps a function like it.
Writing a tiny middleware
The following logger shows the whole idea. It wraps set so each update is printed, then passes the wrapped set to the original creator.
import { create, StateCreator } from 'zustand'
type Logger = <T>(creator: StateCreator<T, [], []>, label?: string) => StateCreator<T, [], []>
const logger: Logger = (creator, label = 'store') => (set, get, api) => {
const loggedSet: typeof set = (...args) => {
console.log(`${label}: before`, get())
set(...args)
console.log(`${label}: after`, get())
}
return creator(loggedSet, get, api)
}
interface CounterState {
count: number
increment: () => void
}
export const useCounterStore = create<CounterState>()(
logger(
(set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}),
'counter',
),
)Calling increment now logs the state before and after. The action itself did not change. It still calls set, but set is now loggedSet.
The StateCreator<T, [], []> type has empty arrays for the middleware lists. That is enough for a middleware that does not change the types of set, get or the store API. Middleware that adds new methods, such as persist adding store.persist, uses those lists to describe the changes. You rarely write them by hand, because the built-in middleware already declares them.
The flow of a call
The diagram shows how an update travels through two wrapped layers.
Each layer sees the call, can do its own work, and forwards it to the next layer.
Composing middleware
Middleware composes by nesting. The outermost call is the outermost wrapper.
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
interface CartState {
items: string[]
isOpen: boolean
addItem: (item: string) => void
toggleOpen: () => void
}
export const useCartStore = create<CartState>()(
devtools(
persist(
(set) => ({
items: [],
isOpen: false,
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
toggleOpen: () => set((state) => ({ isOpen: !state.isOpen })),
}),
{
name: 'cart-storage',
partialize: (state) => ({ items: state.items }),
},
),
{ name: 'CartStore' },
),
)Read it from the inside out. Your creator is wrapped by persist, which saves items to localStorage under cart-storage. That result is wrapped by devtools, which exposes the store to Redux DevTools under the name CartStore.
Note the create<CartState>()(...) form. The extra pair of parentheses lets TypeScript infer the middleware's type changes while you supply CartState explicitly. Without it, middleware typing often fails to infer.
Order matters
The order changes which layer sees the original call. A few practical rules:
- Put
devtoolson the outside, so it sees updates after the inner middleware has handled them. - Put
immerinsidepersistanddevtools, so that the outer layers receive an ordinarysetcall with an ordinary result. - Put
persistoutsideimmerwhen you want the saved data to be the plain result of the update.
A store combining all three looks like this:
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
interface Todo {
id: number
title: string
done: boolean
}
interface TodoState {
todos: Todo[]
toggle: (id: number) => void
}
export const useTodoStore = create<TodoState>()(
devtools(
persist(
immer((set) => ({
todos: [{ id: 1, title: 'Write tutorial', done: false }],
toggle: (id) =>
set((state) => {
const todo = state.todos.find((t) => t.id === id)
if (todo) todo.done = !todo.done
}),
})),
{ name: 'todo-storage' },
),
{ name: 'TodoStore' },
),
)This needs the immer package installed. The toggle action mutates a draft, immer turns that into an immutable update, and persist and devtools receive the finished result.
What middleware can change
Middleware can touch four things:
| Part | Example | What the wrapper does |
|---|---|---|
| `set` | `immer`, `devtools` | Replaces `set` so updates are transformed or reported |
| `get` | rarely changed | Usually passed through unchanged |
| Store API | `persist` | Adds methods such as `useStore.persist.rehydrate()` |
| Initial state | `persist` | Merges saved state in after the creator runs |
The store API row is why typing matters. After wrapping with persist, useCartStore.persist exists, and TypeScript knows about it only if the middleware types were applied.
Common errors
- Calling
createwithout the second pair of parentheses.create<CartState>(devtools(...))can produce type errors or lose middleware methods. Usecreate<CartState>()(...). - Forgetting that middleware runs once per store. The wrapping happens when the store is created, not on every
set. Do not create a store inside a component, because each render would build a new one with new wrappers. - Defining actions outside the creator. An action that does not receive the wrapped
setbypasses the middleware.persistwill not save its changes anddevtoolswill not show them. - Putting
immeroutside other middleware. The layers inside it then receivesetcalls with draft-mutating functions they do not understand. - Mixing mutation and return in one immer recipe. In an
immerrecipe, either mutate the draft or return a new value. Doing both throws an error.
Naming actions in devtools
devtools accepts a third argument to set, a label for the action. It appears in the Redux DevTools timeline.
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
interface CounterState {
count: number
increment: () => void
}
export const useCounterStore = create<CounterState>()(
devtools(
(set) => ({
count: 0,
increment: () =>
set((state) => ({ count: state.count + 1 }), undefined, 'counter/increment'),
}),
{ name: 'Counter' },
),
)The second argument is replace, so pass undefined to keep the merge behavior. This extra argument is an example of a middleware extending the signature of set.
Exercises
Exercise
A teammate writes create<CartState>(devtools(persist(creator, options))) and useCartStore.persist is flagged by TypeScript as missing. What is the most likely fix, and why?
Show answer
Use the curried form create<CartState>()(devtools(persist(creator, options))). The extra parentheses let TypeScript infer the middleware's added types, including the persist property on the store API.
Exercise
You combine persist and immer. Which one should be on the outside, and why does an action that mutates a draft still save correctly?
Show answer
persist goes on the outside and immer on the inside. The immer layer converts the draft mutation into an ordinary immutable update before the call reaches the core store, so persist sees and saves the finished state.
Exercise
What does a middleware receive and return, and why can create accept a wrapped creator without any changes?
Show answer
It receives a state creator and returns a new state creator. Both have the same shape, (set, get, api) => initialState, so create treats them the same.