Sub topic 3
How Middleware Wraps a Store
Assume React hooks, modules, immutable updates, and basic Zustand stores. Middleware is a function that wraps a store creator to add behavior without placing that behavior in every action.
Persisting and Inspecting State
persist saves selected state and restores it when the application starts. devtools connects the store to Redux DevTools for action and state inspection.
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
type CartState = {
items: string[]
isOpen: boolean
addItem: (item: string) => void
}
export const useCartStore = create<CartState>()(
devtools(
persist(
(set) => ({
items: [],
isOpen: false,
addItem: (item) =>
set((state) => ({ items: [...state.items, item] }), false, 'cart/addItem'),
}),
{
name: 'cart-storage',
partialize: (state) => ({ items: state.items }),
},
),
{ name: 'CartStore' },
),
)The partialize option prevents transient UI state, such as isOpen, from being persisted. Storage hydration can briefly differ from the server-rendered state, so account for that in server-rendered applications.
Nested Updates with Immer
immer lets an action mutate a draft while Immer creates the immutable result. Install immer separately.
import { immer } from 'zustand/middleware/immer'
const useTodoStore = create(
immer<{ todos: { id: number; done: boolean }[]; toggle: (id: number) => void }>(
(set) => ({
todos: [{ id: 1, done: false }],
toggle: (id) => set((state) => {
const todo = state.todos.find((item) => item.id === id)
if (todo) todo.done = !todo.done
}),
}),
),
)Slices and Per-Tree Stores
For a large store, define slices as state creators and combine them with one shared set and get. This keeps domain code separate while preserving one store.
A module-level store is global to the application. Use createStore with React context when each provider needs its own instance, such as separate editors or request-scoped state.
Testing and Pitfalls
Because module stores persist between tests, capture the initial state and replace the state before each test:
const initialState = useCartStore.getState()
beforeEach(() => useCartStore.setState(initialState, true))Select only the fields a component needs. Selecting the whole store causes unrelated updates to re-render it. Use useShallow for several fields. Avoid duplicating derived values in state, and choose another solution when server cache, URL state, or complex event workflows are the real problem.
Exercise
Why should a persisted store usually exclude isOpen?
Show answer
isOpen is transient UI state. Persisting it can reopen the interface unexpectedly and create hydration mismatches.