Use persist to keep browser-side store data across reloads. This example draws a position tracker, restores its saved coordinates when you reload, and then shows how to save coordinates without saving the movement count.
Start from the project in the React quick start. It already installs Zustand; the middleware needs no additional package. These samples run in the browser.
Persist
Wrap the state creator with persist, give the store a unique storage key, and consume the resulting store in a mounted component. persist returns a state creator, not a separate store or React component.
Persist middleware
- Add
src/position-store.ts.createbinds the persisted store to a React hook. Omitstorageto use the default JSON adapter forlocalStorage. - Choose a
namespecific to this store and application. Stores sharing the same storage backend and key read and overwrite the same item.
tsimport { create } from 'zustand'
import { persist } from 'zustand/middleware'
type PositionState = {
position: { x: number; y: number }
moves: number
setPosition: (position: PositionState['position']) => void
}
export const usePositionStore = create<PositionState>()(
persist(
(set) => ({
position: { x: 40, y: 40 },
moves: 0,
setPosition: (position) =>
set((state) => ({ position, moves: state.moves + 1 })),
}),
{
name: 'position-tracker/local',
onRehydrateStorage: () => (_state, error) => {
if (error) console.error('Unable to restore the position tracker', error)
},
},
),
)
Updates through set write the current state to storage. The JSON adapter writes an envelope containing state and version; the default version is 0. On store initialization, persist reads that envelope and shallowly merges the saved data into the initial state. With synchronous browser storage, this happens during initialization, before the component reads the store.
Persisting a state
- Add this component. Move the pointer inside the box to update the coordinates and the movement count. The red dot follows the pointer.
- Mount
PositionTrackerin place of the counter using the React quick start's mounting step.
tsximport { usePositionStore } from './position-store'
export default function PositionTracker() {
const position = usePositionStore((state) => state.position)
const moves = usePositionStore((state) => state.moves)
const setPosition = usePositionStore((state) => state.setPosition)
return (
<main>
<h1>Persisted position</h1>
<p>Position: {Math.round(position.x)}, {Math.round(position.y)}</p>
<p>Pointer updates: {moves}</p>
<button
type="button"
onClick={() => {
if (window.confirm('Replace the current tracker state with the saved state?')) {
void usePositionStore.persist.rehydrate()
}
}}
>
Restore saved state
</button>
<div
style={{ position: 'relative', width: 320, height: 240, background: '#eee' }}
onPointerMove={(event) => {
const bounds = event.currentTarget.getBoundingClientRect()
setPosition({
x: event.clientX - bounds.left,
y: event.clientY - bounds.top,
})
}}
>
<div
style={{
position: 'absolute',
left: position.x,
top: position.y,
width: 20,
height: 20,
borderRadius: '50%',
background: 'red',
transform: 'translate(-50%, -50%)',
pointerEvents: 'none',
}}
/>
</div>
</main>
)
}
- Run the project:
bashnpm run build npm run dev
Open Vite's local URL. With no saved item, the dot starts at (40, 40) and the counter starts at 0. Move the pointer, then reload without moving it back into the box: the saved position and count return. Each pointer update saves automatically; there is no Save button. To read the saved item again without reloading the page, click Restore saved state and confirm. The button calls rehydrate() once, leaving parsing and merging to the middleware.
Automatic restoration runs once when this store initializes. The explicit restore button asks before replacing current state. Because each update saves immediately, restoring normally leaves the displayed position unchanged; in the partial-storage variant, it also preserves the current movement count because that field is absent from storage. For hydration controls, continue with Control state hydration.
Persisting a state partially
Use partialize to select saved fields without removing other fields from the live store. Use createJSONStorage when choosing a different string-based storage backend.
- Replace the store module below; keep
PositionTracker.tsxand its mount unchanged. This variant saves onlyposition, and usessessionStoragerather than the defaultlocalStorage. - Move the pointer and reload the same tab. The coordinates return, but the movement count starts at
0.
tsimport { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
type PositionState = {
position: { x: number; y: number }
moves: number
setPosition: (position: PositionState['position']) => void
}
export const usePositionStore = create<PositionState>()(
persist(
(set) => ({
position: { x: 40, y: 40 },
moves: 0,
setPosition: (position) =>
set((state) => ({ position, moves: state.moves + 1 })),
}),
{
name: 'position-tracker/session',
storage: createJSONStorage(() => sessionStorage),
partialize: (state) => ({ position: state.position }),
onRehydrateStorage: () => (_state, error) => {
if (error) console.error('Unable to restore the position tracker', error)
},
},
),
)
The separate key keeps this variant's data separate from the first example. sessionStorage retains data across reloads in the same page session; use the default localStorage when you want persistence beyond that session. partialize filters each write, not the live state: the counter still updates while the app runs.
What survives the round trip
| Field | Default-storage example | Partial-storage example |
|---|---|---|
position | Saved and restored | Saved and restored |
moves | Saved and restored | Omitted; starts at the initializer's 0 |
setPosition | JSON omits the function; the initializer supplies it again | Excluded by partialize; the initializer supplies it again |
Keep persisted data JSON-compatible. Functions do not survive JSON serialization; object types such as Maps and Sets need an explicit conversion in a custom storage adapter.
Options that matter
| Option | Type | Default | What it does |
|---|---|---|---|
name | string | Required | Identifies the storage item; choose a unique key. |
storage | PersistStorage | JSON adapter for localStorage | Chooses the backend used to read and write the envelope. |
partialize | (state: S) => PersistedState | Returns the whole state | Selects the state written to storage. |
onRehydrateStorage | (state: S) => ((state?: S, error?: unknown) => void) | void | Unset | Runs before hydration; its returned callback receives completion or an error. |
version | number | 0 | Rejects a stored numeric version that differs unless migrate handles it. |
migrate | (persistedState: unknown, version: number) => PersistedState | Promise<PersistedState> | Unset | Converts stored data after a version mismatch. |
merge | (persistedState: unknown, currentState: S) => S | Shallow merge | Combines restored data with current state. |
skipHydration | boolean | false | false restores automatically on initialization; true defers loading until you call rehydrate(). |
Pitfalls
- The JSON adapter parses data but does not validate its shape. Malformed JSON reaches the error callback in these samples and is logged rather than partially applied. Valid JSON with incorrect fields is not rejected by type checking or by the adapter; use a validating custom storage adapter for untrusted data. The version field is a compatibility marker, not an integrity check.
createJSONStoragecalls the supplied storage getter when you create the adapter. If obtaining storage throws, it returnsundefined. Use browser storage in browser-side code; see Server-render React stores for server-rendered applications.- For asynchronous storage and first-render readiness, see Control state hydration.
- For version changes or partially saved nested objects, see Migrate persisted data.
Live demo and related guides
Explore the live Zustand demo for the store-hook and action pattern used here. The authors' persistence reference develops the position-tracker example with additional storage and hydration choices.
- Control state hydration adds loading control and hydration-aware UI.
- Migrate persisted data covers schema versions and custom merges.
- Implement custom storage covers adapters beyond browser storage.
Was this page helpful?