Identify a persisted store entry
Saving client-side state across reloads
Zustand · Pipe
The persist middleware's required name option is the storage key for a Zustand store's persisted state. It must be unique.
The persist middleware requires a name option and uses its string value as the key under which the Zustand state is stored. The key must be unique within the selected storage, such as localStorage, AsyncStorage, or IndexedDB.
persist(stateCreator, { name: string })| Name | Type | Description |
|---|---|---|
name | string | The unique storage key used for the persisted Zustand state. |
The documentation does not specify a separate return value for the name option.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type BearStore = {
bears: number
addBear: () => void
}
const useBearStore = create<BearStore>()(
persist(
(set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
}),
{ name: 'bear-storage' },
),
)
export function App() {
const bears = useBearStore((state) => state.bears)
return <button onClick={useBearStore.getState().addBear}>{bears}</button>
}The persist middleware uses the supplied name as the storage key for this store.
Saving client-side state across reloads
Maintaining several persisted stores
Using different persistence backends
The name option is the storage key for the persisted Zustand state. It is the only required persist option, and its value identifies the entry in the configured storage.
Follow-up: What should be checked if two stores interfere with each other? Verify that their persist names are different, because the name must be unique.
Pass name inside the second argument to persist, alongside the store initializer. For example, persist((set) => ({ count: 0 }), { name: 'counter-storage' }).
Follow-up: Can the option be omitted? No. The documentation identifies name as the only required option.
The option does not itself choose a storage implementation; it supplies the key used by the middleware in the storage where state is persisted. The documentation lists localStorage, AsyncStorage, and IndexedDB as examples of storage targets.
Follow-up: How can the storage target be changed? Configure the persist middleware's storage-related options while retaining a unique name for the entry.
persiststoragelocalStorageAsyncStorageIndexedDB