Skip to content
D
Documentation

Migrate persisted data

how-to
4 min readUpdated

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. 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 binds the store to a React hook; 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
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.

Merge partially persisted nested objects

  1. 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
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

  1. 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.
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>,
)
  1. 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

DataKept or lost
Version 0 x and yKept as position.x and position.y; the old top-level names are not returned.
Current nested defaultsKept where the saved position omits a coordinate.
Saved nested coordinatesKept in preference to the corresponding defaults.
ActionsNot saved by partialize; the current initializer supplies setPosition.
Other saved fieldsDiscarded 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

OptionTypeDefaultWhat it does
namestringRequiredSelects the storage key; keep it stable across schema versions.
versionnumber0Identifies the saved schema; a differing numeric stored version triggers migration.
migrate(persistedState: unknown, version: number) => PersistedState | Promise<PersistedState>Not providedConverts mismatched-version state into the current saved shape. Without it, mismatched-version data is not used.
merge(persistedState: unknown, currentState: State) => StateShallow current-then-saved mergeCombines restored data with the full current state, including actions.
partialize(state: State) => PersistedStateIdentity functionChooses what gets written; this example saves only position.
onRehydrateStorage(state: State) => ((state?: State, error?: unknown) => void) | voidNot providedRuns before hydration and optionally returns a completion/error callback.

Explore the live Zustand demo for store-driven React rendering. For the coordinate migration and nested-merge examples this page follows, read the authors' persist examples.

Was this page helpful?

Migrate persisted data — zustand · GPT-6.1 Sol