Sub topic 12
Inspecting state with Redux DevTools
This chapter assumes you can write a Zustand store with create, call set from actions, and wrap a store in middleware as covered in the previous chapters. You don't need Redux experience. You only need the browser extension, which Zustand talks to through a small middleware.
What the devtools middleware does
The Redux DevTools browser extension (available for Chrome, Firefox and Edge) shows a log of state changes, the state after each change, and the difference between two states. It was built for Redux, but any library can send it data. Zustand's devtools middleware does this.
The middleware wraps your state creator and replaces set with a version that does two extra things:
- It applies the update as usual.
- It sends the action name and the new state to the extension.
It also listens for messages from the extension, such as "jump to this state". When you click an earlier entry in the log, the middleware calls setState with that older state, and your components re-render to match.
Adding devtools to a store
Wrap the state creator in devtools. With TypeScript, keep the create<T>()(...) form so the middleware types work.
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
interface CounterState {
count: number
increment: () => void
reset: () => void
}
export const useCounterStore = create<CounterState>()(
devtools(
(set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}),
{ name: 'CounterStore' },
),
)Open your app in a browser with the extension installed, open the browser's developer tools, and select the Redux tab. The instance dropdown lists CounterStore. Click the button that calls increment and an entry appears in the log.
The name option sets the instance label. If you have several stores and give none a name, they are hard to tell apart in the dropdown. Give every store a distinct name.
Naming actions
The log entry for the example above is called anonymous. Zustand's set doesn't know which action called it, because set is only a function that merges state. A log full of anonymous entries tells you almost nothing.
With devtools, set accepts a third argument, the action name. The second argument is the replace flag. Pass false to keep the normal merge behavior.
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
interface CartState {
items: string[]
isOpen: boolean
addItem: (item: string) => void
clear: () => void
toggleOpen: () => void
}
export const useCartStore = create<CartState>()(
devtools(
(set) => ({
items: [],
isOpen: false,
addItem: (item) =>
set((state) => ({ items: [...state.items, item] }), false, 'cart/addItem'),
clear: () => set({ items: [] }, false, 'cart/clear'),
toggleOpen: () =>
set((state) => ({ isOpen: !state.isOpen }), false, { type: 'cart/toggleOpen' }),
}),
{ name: 'CartStore' },
),
)The third argument can be a string or an object with a type field. The object form lets you attach extra fields, such as a payload, which the extension shows next to the action. A string is enough for most cases.
You can also change the label for unnamed updates with the anonymousActionType option. This makes a missing name easier to find:
devtools(stateCreator, { name: 'CartStore', anonymousActionType: 'UNNAMED_UPDATE' })Searching the log for UNNAMED_UPDATE then shows which calls still need a name.
Using the extension
Once actions are named, three views in the extension help most.
- Action log. Each entry is one
setcall. Click an entry to see the state at that point. - Diff. Shows what changed between the selected entry and the one before it. If you expected one field to change and the diff shows three, an action is writing more than it should.
- Jump and skip. Jump moves the store to a past state. Skip removes one action from the history and replays the rest. Both call
setStateon your store, so they test whether your UI renders correctly for any state.
Time travel only restores state held in the store. Anything outside it does not rewind: local useState, data already fetched, timers, and database writes. If jumping back leaves the UI inconsistent, check whether an effect or a component's own state depends on the store value but isn't derived from it.
Combining with other middleware
Order matters when you stack middleware. Each one wraps the one inside it, and devtools can only report the set calls it sees. The usual advice is to make devtools the outermost wrapper, as in the persist example from the earlier chapter:
create<CartState>()(
devtools(
persist(stateCreator, { name: 'cart-storage' }),
{ name: 'CartStore' },
),
)With devtools outside, every update passes through it, including the one persist makes when it restores saved state at startup. Because persist is inside, it receives the original set, so its internal rehydration is not named in the log. Put immer inside devtools as well. If you reverse the order, TypeScript often fails to infer the third set argument, and the compiler error is hard to read.
Turning it off in production
By default the middleware is active in development builds and inactive in production builds. If the extension isn't installed, nothing is sent and the store works normally. You can control this with enabled:
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
interface ThemeState {
dark: boolean
toggle: () => void
}
export const useThemeStore = create<ThemeState>()(
devtools(
(set) => ({
dark: false,
toggle: () => set((state) => ({ dark: !state.dark }), false, 'theme/toggle'),
}),
{ name: 'ThemeStore', enabled: import.meta.env.DEV },
),
)import.meta.env.DEV is a Vite variable. Other bundlers use different names, such as process.env.NODE_ENV !== 'production'. Setting enabled explicitly makes your intent clear, and it keeps state out of the extension in builds you ship.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The Redux tab shows no instances | Extension missing, or `enabled` is false | Install the extension, and check the `enabled` option and the build mode |
| Every entry is named `anonymous` | `set` called without the third argument | Pass an action name, or set `anonymousActionType` to find the gaps |
| Two stores are hard to tell apart | No `name`, or the same `name` on both | Give each store a unique `name` |
| TypeScript error on the third `set` argument | `create(...)` used without the `<T>()` call, or the middleware order is wrong | Use `create<T>()(devtools(...))` and keep `devtools` outermost |
| UI is wrong after time travel | State kept outside the store | Derive the UI from store values, or move that state into the store |
Safety notes
Exercise
A store is created with create<TodoState>()(devtools(persist(stateCreator, { name: 'todos' }), { name: 'TodoStore' })). In the Redux tab every entry from the addTodo action is labeled anonymous. The action is addTodo: (title) => set((state) => ({ todos: [...state.todos, title] })). What change gives these entries a useful label, and which option would make any remaining unnamed updates easy to find?
Show answer
Pass false as the second argument and an action name as the third: set((state) => ({ todos: [...state.todos, title] }), false, 'todos/add'). Set anonymousActionType: 'UNNAMED_UPDATE' in the devtools options, so any update still missing a name appears under that label.