Sub topic 10
How middleware wraps a store
This chapter assumes you can write a store with create, know that set merges partial state, and read TypeScript generics. It builds on the typed create<T>()(...) form.
What middleware is
A state creator is the function you pass to create. It receives set, get and api, and it returns the initial state object.
Middleware is a function that takes a state creator and returns a new state creator. The new one can change the set, get or api it hands to the creator it wraps. It can also add behavior around them. The store never knows middleware exists. It only sees a state creator.
Composing middleware
You nest middleware by calling one inside another. This store is from the earlier example:
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
interface CartState {
items: string[]
addItem: (item: string) => void
}
export const useCartStore = create<CartState>()(
devtools(
persist(
(set) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
}),
{ name: 'cart-storage' },
),
{ name: 'CartStore' },
),
)Read it from the inside out. Your creator is wrapped by persist, and persist is wrapped by devtools. When a component calls addItem, the call passes through each layer's version of set until it reaches the real one.
Order matters. The outer layer sees whatever the inner layers expose. Putting devtools outermost means it reports updates that persist makes, such as rehydrating from storage.
Writing your own middleware
A small logger shows the mechanism. It replaces set with a version that logs the state before and after each update.
import { create, StateCreator } from 'zustand'
const logger =
<T,>(creator: StateCreator<T, [], []>): StateCreator<T, [], []> =>
(set, get, api) => {
const loggedSet: typeof set = (...args) => {
console.log('before', get())
set(...(args as Parameters<typeof set>))
console.log('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 })),
})),
)The inner creator receives loggedSet, so every set call in your actions goes through the logger without any change to the actions.
Common errors
- Forgetting the second pair of parentheses. Middleware typing only works with
create<T>()(...). Writingcreate<T>(...)loses type inference for the wrapped creator. - Putting the creator outside the middleware. The creator is the first argument of
persistanddevtools. Options come second. - Assuming order does not matter. Swapping layers can change what a layer observes. Check the middleware's documentation when you combine more than two.
- Typing a custom middleware too loosely.
StateCreator<T, [], []>works for a simple wrapper. Middleware that adds fields toapineeds the mutator type parameters filled in.
Exercise
In create<S>()(devtools(persist(creator, persistOptions), devtoolsOptions)), which function receives the real set first, and which function does your creator receive set from?
Show answer
devtools is outermost, so it receives the real set from create. It passes its own version to persist, and persist passes its version to creator. Your creator therefore calls set through both layers.