Sub topic 11
Persisting state to storage
This chapter assumes you can create a store with create, update it with set, and compose middleware as covered in the previous chapter. By default, a Zustand store lives in memory, so a page reload resets it. The persist middleware saves state to a storage area and restores it when the store is created.
Adding persist to a store
persist wraps your state creator. The name option is required. It is the key under which the data is saved. The default storage is localStorage.
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' },
),
)partialize chooses which fields to save. Here only items is stored. isOpen is UI state, so it starts as false on every load. Functions are never saved, because state is serialized as JSON. Only plain data survives.
What happens on load and on update
The merge on startup is shallow by default. Saved top-level fields replace the initial ones. Fields you did not save keep their initial values.
Choosing another storage
Use createJSONStorage to pick a different storage area, such as sessionStorage. Use version and migrate to handle saved data from an older shape.
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
interface SettingsState {
theme: 'light' | 'dark'
setTheme: (theme: 'light' | 'dark') => void
}
export const useSettingsStore = create<SettingsState>()(
persist(
(set) => ({
theme: 'light',
setTheme: (theme) => set({ theme }),
}),
{
name: 'settings',
version: 1,
storage: createJSONStorage(() => sessionStorage),
migrate: (persisted, version) => {
const old = persisted as Partial<SettingsState> & { dark?: boolean }
if (version === 0) {
return { ...old, theme: old.dark ? 'dark' : 'light' } as SettingsState
}
return old as SettingsState
},
},
),
)If the stored version differs from version, Zustand calls migrate with the old data. Without a migrate function, mismatched data is discarded.
Common errors
- Saving everything. Without
partialize, all data fields are written, including loading flags and errors. Save only what should survive a reload. - Changing the state shape without bumping
version. Old saved data then merges into the new shape and can leave fields with the wrong type. - Server rendering. Storage does not exist on the server. The first client render can differ from the server HTML and cause a hydration mismatch. The
skipHydrationoption lets you restore state manually after mount. - Sensitive data.
localStorageis readable by any script on the page. Do not persist tokens or personal data there.
Exercise
A store holds user, isLoading and error. You want only user to survive a page reload. Which option do you set on persist, and what does it look like?
Show answer
Set partialize: partialize: (state) => ({ user: state.user }). Only user is written to storage. isLoading and error keep their initial values after a reload.