# Migrate persisted data

Use a storage version when you change the shape of saved state. This example moves version 0's separate `x` and `y` fields into `position`, then merges saved coordinates with current nested defaults. You see two red dots: one restored from the old shape, and one restored from a nested object that omits `x`.

Start in the client-rendered project from the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start). Zustand is already installed there; if you are adding this to another React project, run:

```bash
npm install zustand
```

## Migrate the saved shape

1. Add the store factory below. [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) binds the store to a React hook; [`persist`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#persist) reads saved state during initialization. Set `version: 1` and return the current saved shape from `migrate` when the stored version is 0.

   The factory lets the two demonstrations use separate storage keys. Defining it does not create a store or read storage; the entry file calls it.

```ts title="src/position-store.ts"
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

type Position = { x: number; y: number }
type SavedPosition = { position: Partial<Position> }
type PositionState = {
  position: Position
  setPosition: (position: Position) => void
}

function readPosition(value: unknown): Partial<Position> {
  if (typeof value !== 'object' || value === null) {
    throw new Error('Saved coordinates must be an object')
  }
  const position: Partial<Position> = {}
  if ('x' in value) {
    if (typeof value.x !== 'number' || !Number.isFinite(value.x)) {
      throw new Error('Saved x must be a finite number')
    }
    position.x = value.x
  }
  if ('y' in value) {
    if (typeof value.y !== 'number' || !Number.isFinite(value.y)) {
      throw new Error('Saved y must be a finite number')
    }
    position.y = value.y
  }
  return position
}

function readSavedPosition(value: unknown): SavedPosition {
  if (typeof value !== 'object' || value === null || !('position' in value)) {
    throw new Error('Saved state must contain position')
  }
  return { position: readPosition(value.position) }
}

export function createPositionStore(name: string) {
  let hydrationError = ''
  const usePositionStore = create<PositionState>()(
    persist(
      (set) => ({
        position: { x: 40, y: 40 },
        setPosition: (position) => set({ position }),
      }),
      {
        name,
        version: 1,
        partialize: (state): SavedPosition => ({ position: state.position }),
        migrate: (saved, version): SavedPosition => {
          if (version !== 0) {
            throw new Error(`Unsupported saved version: ${version}`)
          }
          return { position: readPosition(saved) }
        },
        merge: (saved, current) => {
          if (saved === undefined) return current
          const restored = readSavedPosition(saved)
          return {
            ...current,
            position: { ...current.position, ...restored.position },
          }
        },
        onRehydrateStorage: () => (_state, error) => {
          if (error) {
            hydrationError = error instanceof Error ? error.message : String(error)
            console.error('Position restoration failed', error)
          }
        },
      },
    ),
  )
  return { usePositionStore, hydrationError }
}
```

`migrate` receives the **stored** version, not the target version. It runs only when a numeric stored version differs from the configured version. Its return value can also be a promise. A successful migration is merged into the store and written back with the configured version. If the versions match, hydration passes the saved state straight to `merge`, so validation belongs there too.

This synchronous, browser-only example uses the default JSON-backed `localStorage`. It captures hydration errors during store creation and displays them in the component below. For asynchronous storage and reactive hydration status, use [Control state hydration](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/control-persisted-state-hydration).

## Merge partially persisted nested objects

2. Add the component below. The `merge` function above copies the current state first, then overlays saved coordinates inside `position`. This preserves a missing `x` and the current `setPosition` action.

   `persist` shallowly merges restored data by default. A saved `{ position: { y: 100 } }` replaces the entire current `position` object and erases its `x`. Supply a custom nested merge, as above, or a deep merge appropriate to your schema.

```tsx title="src/PositionDemo.tsx"
import type { createPositionStore } from './position-store'

type PositionDemoProps = {
  title: string
  store: ReturnType<typeof createPositionStore>
}

export default function PositionDemo({ title, store }: PositionDemoProps) {
  const { usePositionStore, hydrationError } = store
  const position = usePositionStore((state) => state.position)
  const setPosition = usePositionStore((state) => state.setPosition)

  return (
    <section>
      <h2>{title}</h2>
      {hydrationError && <p role="alert">Restoration failed: {hydrationError}</p>}
      <p>x: {position.x}, y: {position.y}</p>
      <div
        style={{ position: 'relative', width: 300, height: 240, border: '1px solid' }}
        onPointerMove={(event) => {
          const bounds = event.currentTarget.getBoundingClientRect()
          setPosition({
            x: Math.round(event.clientX - bounds.left),
            y: Math.round(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>
      <p>Move the pointer inside the box to move and save the dot.</p>
      <button
        type="button"
        onClick={() => usePositionStore.setState({
          position: usePositionStore.getState().position,
        })}
      >
        Save current position
      </button>
    </section>
  )
}
```

The hook's selectors keep the displayed coordinates and dot in sync with the store. Pointer movement invokes the action and saves the new position. **Save current position** explicitly writes the current coordinates even if you have not moved the dot: creating a store without an existing saved value does not save its defaults.

## Run migration and restoration

3. Seed the two saved-data fixtures before creating their stores, then render both position demonstrations; retain the entry-file setup from the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start).

```tsx title="src/main.tsx"
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import PositionDemo from './PositionDemo'
import { createPositionStore } from './position-store'

// Demonstration fixtures only: never overwrite an existing saved value.
if (localStorage.getItem('migration-position-demo') === null) {
  localStorage.setItem('migration-position-demo', JSON.stringify({
    state: { x: 100, y: 100 },
    version: 0,
  }))
}
if (localStorage.getItem('nested-position-demo') === null) {
  localStorage.setItem('nested-position-demo', JSON.stringify({
    state: { position: { y: 100 } },
    version: 1,
  }))
}

const migratedStore = createPositionStore('migration-position-demo')
const nestedStore = createPositionStore('nested-position-demo')

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <main style={{ minHeight: 400 }}>
      <h1>Persisted positions</h1>
      <PositionDemo title="Migrated version 0" store={migratedStore} />
      <PositionDemo title="Partial nested position" store={nestedStore} />
    </main>
  </StrictMode>,
)
```

4. Build and start the project:

```bash
npm run build
npm run dev
```

On a first visit with these keys absent, the first dot appears at `(100, 100)`. The second appears at `(40, 100)`: saved `y` wins, while missing `x` keeps its current default. On later visits, the dots use your saved coordinates.

Move either dot, then reload the page to restore it. Each store loads once during creation, before you can edit it; no second parser or manual rehydration replaces newer edits. The direct storage writes above only seed old-format demonstration data. In your app, let `persist` write the versioned envelope.

### What survives the migration

| Data | Kept or lost |
| --- | --- |
| Version 0 `x` and `y` | Kept as `position.x` and `position.y`; the old top-level names are not returned. |
| Current nested defaults | Kept where the saved position omits a coordinate. |
| Saved nested coordinates | Kept in preference to the corresponding defaults. |
| Actions | Not saved by `partialize`; the current initializer supplies `setPosition`. |
| Other saved fields | Discarded by this schema-specific reader and migration. |

Zustand's JSON storage format contains `state` and `version`; it is not an integrity checksum or a schema validator. Here, malformed JSON, unsupported numeric versions, and invalid coordinate types report a restoration error and leave the default position visible. Matching-version data also passes through the coordinate validator. Do not treat a version number alone as proof that external data is valid.

## Options that matter

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `name` | `string` | Required | Selects the storage key; keep it stable across schema versions. |
| `version` | `number` | `0` | Identifies the saved schema; a differing numeric stored version triggers migration. |
| `migrate` | `(persistedState: unknown, version: number) => PersistedState \| Promise<PersistedState>` | Not provided | Converts mismatched-version state into the current saved shape. Without it, mismatched-version data is not used. |
| `merge` | `(persistedState: unknown, currentState: State) => State` | Shallow current-then-saved merge | Combines restored data with the full current state, including actions. |
| `partialize` | `(state: State) => PersistedState` | Identity function | Chooses what gets written; this example saves only `position`. |
| `onRehydrateStorage` | `(state: State) => ((state?: State, error?: unknown) => void) \| void` | Not provided | Runs before hydration and optionally returns a completion/error callback. |

## Demo and related guides

Explore the [live Zustand demo](https://zustand-demo.pmnd.rs/) for store-driven React rendering. For the coordinate migration and nested-merge examples this page follows, read the [authors' persist examples](https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/persist.md).

- [Persist store state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/persist-store-state) covers choosing which state to save.
- [Control state hydration](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/control-persisted-state-hydration) covers delayed and manual restoration.
- [Migrate stores to v5](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/migrate-stores-to-v5) covers upgrading the library rather than your saved schema.
