Sub topic 11
Persisting state to storage
This chapter shows how to save a Zustand store to browser storage and restore it on the next page load. It assumes you can create a store, select state with selectors, and write actions with set. It also assumes you know what localStorage is. The previous chapter showed that middleware wraps the state creator. persist is one such wrapper.
What persist does
The persist middleware does two jobs:
- After every state change, it serializes the state and writes it to a storage.
- When the store is created, it reads that storage and merges the saved values over the initial state.
By default the storage is localStorage and the format is JSON. JSON has no representation for functions, Map, Set or Date. Functions are dropped when saving, and the other types do not come back as the same type. This is why actions survive a reload: they live in your code and are never read from storage.
The following diagram shows the flow.
A basic persisted store
Wrap the state creator in persist and give it a unique name. That name is the storage key.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface PrefsState {
theme: 'light' | 'dark'
setTheme: (theme: 'light' | 'dark') => void
}
export const usePrefsStore = create<PrefsState>()(
persist(
(set) => ({
theme: 'light',
setTheme: (theme) => set({ theme }),
}),
{ name: 'prefs-storage' },
),
)After setTheme('dark'), open your browser's developer tools and look at Application, then Local Storage. You will see a key prefs-storage with a value like this:
{"state":{"theme":"dark"},"version":0}The saved object has a state field and a version field. The version field matters later, in the migration section.
Choosing what to save with partialize
Persisting everything is often wrong. Loading flags, open menus and error messages should start fresh on every visit. The partialize option takes the full state and returns the subset to write.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface CartState {
items: string[]
isOpen: boolean
addItem: (item: string) => void
toggleOpen: () => void
}
export const useCartStore = create<CartState>()(
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 }),
},
),
)Only items is written. On reload, isOpen comes from the initial state, so the cart panel starts closed.
Choosing the storage
Use the storage option to change where data goes. Wrap a storage getter with createJSONStorage. The getter is a function so the storage is not touched until it is needed.
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
interface DraftState {
text: string
setText: (text: string) => void
}
export const useDraftStore = create<DraftState>()(
persist(
(set) => ({
text: '',
setText: (text) => set({ text }),
}),
{
name: 'draft-storage',
storage: createJSONStorage(() => sessionStorage),
},
),
)Here the draft survives a reload but is cleared when the tab closes. Any object with getItem, setItem and removeItem works. These methods may return promises, so you can use IndexedDB or React Native's AsyncStorage.
Versions and migrations
Saved data outlives your code. Suppose version 1 of your app stored darkMode: boolean, and version 2 replaces it with theme: 'light' | 'dark'. A returning user still has the old shape in storage.
Set version on the store and supply a migrate function. When the saved version differs from the current one, migrate receives the saved state and its version. It returns the state in the new shape.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface SettingsState {
theme: 'light' | 'dark'
language: string
setTheme: (theme: 'light' | 'dark') => void
}
export const useSettingsStore = create<SettingsState>()(
persist(
(set) => ({
theme: 'light',
language: 'en',
setTheme: (theme) => set({ theme }),
}),
{
name: 'settings-storage',
version: 2,
migrate: (persisted, version) => {
const old = persisted as { darkMode?: boolean; language?: string }
if (version < 2) {
return {
language: old.language ?? 'en',
theme: old.darkMode ? 'dark' : 'light',
} as SettingsState
}
return persisted as SettingsState
},
},
),
)The cast to SettingsState is there because the saved object has no actions. The merge step supplies them from the initial state.
Hydration
Loading saved data into the store is called hydration. With localStorage, hydration is synchronous: the store already holds restored values when the first component reads it. That is fine in a client-only app.
Two situations break this:
- An async storage such as IndexedDB or AsyncStorage finishes after the first render. Components briefly see the initial state.
- With server rendering, the server has no
localStorage. If the client renders restored values on its first pass, the HTML will not match what the server sent, and React reports a hydration mismatch.
For both cases, set skipHydration: true and trigger it yourself after mount with rehydrate. Use hasHydrated and onFinishHydration to find out when it is done.
import { useEffect, useState } from 'react'
import { useSettingsStore } from './settingsStore'
function useHydrated() {
const [hydrated, setHydrated] = useState(false)
useEffect(() => {
const unsubscribe = useSettingsStore.persist.onFinishHydration(() =>
setHydrated(true),
)
setHydrated(useSettingsStore.persist.hasHydrated())
return unsubscribe
}, [])
return hydrated
}
export function ThemeLabel() {
const hydrated = useHydrated()
const theme = useSettingsStore((state) => state.theme)
return <p>{hydrated ? `Theme: ${theme}` : 'Loading...'}</p>
}This requires skipHydration: true in the store options. Somewhere that runs once on the client, such as a top-level useEffect, call useSettingsStore.persist.rehydrate().
The persist API on the store
persist adds a persist object to the store hook:
| Method | Purpose |
|---|---|
| `persist.rehydrate()` | Reads storage and merges it into the state |
| `persist.hasHydrated()` | Returns `true` once hydration has finished |
| `persist.onFinishHydration(fn)` | Runs `fn` after hydration and returns an unsubscribe function |
| `persist.clearStorage()` | Deletes the saved entry without changing the current state |
| `persist.getOptions()` | Returns the current persist options |
clearStorage is the usual way to implement "log out and forget everything". Pair it with setState to reset the live state too.
Merging and nested state
The default merge is shallow: { ...currentState, ...persistedState }. Top-level keys from storage replace the initial values completely. If you persist a nested object and later add a field to it, returning users keep the old object without the new field.
Combining with devtools
When you combine middleware, order matters because each wrapper sees the one inside it. The usual order puts devtools on the outside and persist inside, as in the cart example from the middleware chapter. Then the devtools see every state change, including the one made when persist restores saved data.
Common errors
- Duplicate names. Two stores with the same
nameoverwrite each other's data. Give every persisted store its own key. - Persisting secrets.
localStorageis readable by any script on the page. Never store tokens you cannot afford to leak. - Storing non-JSON values. A
Datecomes back as a string. ASetbecomes{}. Convert before saving, or use theserialize-style hooks of a custom storage built withcreateJSONStorageoptionsreplacerandreviver. - Changing state shape without bumping
version. Old saved data silently overrides your new defaults for any key it contains. - Flash of initial state. Async storage or
skipHydrationmeans one or more renders before restored values appear. Gate the UI onhasHydrated.
Exercise
A store persists { items, isOpen } under the name cart-storage with no partialize. You ship a release that renames items to products, and you leave version at its default. What do returning users experience, and what two changes fix it?
Show answer
Their saved entry still contains items. It is merged into the state as an extra key, and products starts from the initial value, so the cart appears empty. isOpen is also restored from last time. The fix is to set version: 1 (or higher than the saved one) and add a migrate function that copies items into products. Adding partialize: (state) => ({ products: state.products }) also stops isOpen from being saved.