Skip to content
D
Documentation

Persist store state

how-to
4 min readUpdated

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

  1. Add src/position-store.ts. create binds the persisted store to a React hook. Omit storage to use the default JSON adapter for localStorage.
  2. Choose a name specific to this store and application. Stores sharing the same storage backend and key read and overwrite the same item.
ts
import { 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

  1. Add this component. Move the pointer inside the box to update the coordinates and the movement count. The red dot follows the pointer.
  2. Mount PositionTracker in place of the counter using the React quick start's mounting step.
tsx
import { 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>
  )
}
  1. Run the project:
bash
npm 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.

  1. Replace the store module below; keep PositionTracker.tsx and its mount unchanged. This variant saves only position, and uses sessionStorage rather than the default localStorage.
  2. Move the pointer and reload the same tab. The coordinates return, but the movement count starts at 0.
ts
import { 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

FieldDefault-storage examplePartial-storage example
positionSaved and restoredSaved and restored
movesSaved and restoredOmitted; starts at the initializer's 0
setPositionJSON omits the function; the initializer supplies it againExcluded 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

OptionTypeDefaultWhat it does
namestringRequiredIdentifies the storage item; choose a unique key.
storagePersistStorageJSON adapter for localStorageChooses the backend used to read and write the envelope.
partialize(state: S) => PersistedStateReturns the whole stateSelects the state written to storage.
onRehydrateStorage(state: S) => ((state?: S, error?: unknown) => void) | voidUnsetRuns before hydration; its returned callback receives completion or an error.
versionnumber0Rejects a stored numeric version that differs unless migrate handles it.
migrate(persistedState: unknown, version: number) => PersistedState | Promise<PersistedState>UnsetConverts stored data after a version mismatch.
merge(persistedState: unknown, currentState: S) => SShallow mergeCombines restored data with current state.
skipHydrationbooleanfalsefalse 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.
  • createJSONStorage calls the supplied storage getter when you create the adapter. If obtaining storage throws, it returns undefined. 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.

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.

Was this page helpful?