# Persist store state

Use [`persist`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#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 title="src/position-store.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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#4-mount-the-counter).

```tsx title="src/PositionTracker.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>
  )
}
```

3. 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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/control-persisted-state-hydration).

### Persisting a state partially

Use `partialize` to select saved fields without removing other fields from the live store. Use [`createJSONStorage`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#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 title="src/position-store.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

| 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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/implement-custom-storage).

## Options that matter

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `name` | `string` | Required | Identifies the storage item; choose a unique key. |
| `storage` | [`PersistStorage`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/implement-custom-storage) 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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/server-render-react-stores) for server-rendered applications.
- For asynchronous storage and first-render readiness, see [Control state hydration](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/control-persisted-state-hydration).
- For version changes or partially saved nested objects, see [Migrate persisted data](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/migrate-persisted-data).

## Live demo and related guides

Explore the [live Zustand demo](https://zustand-demo.pmnd.rs/) for the store-hook and action pattern used here. The [authors' persistence reference](https://zustand.docs.pmnd.rs/reference/middlewares/persist) develops the position-tracker example with additional storage and hydration choices.

- [Control state hydration](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/control-persisted-state-hydration) adds loading control and hydration-aware UI.
- [Migrate persisted data](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/migrate-persisted-data) covers schema versions and custom merges.
- [Implement custom storage](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/implement-custom-storage) covers adapters beyond browser storage.
