# Migrate stores to v5

Use this migration when an older store needs current imports and typings, custom equality, stable selector outputs, or updated replacement and persistence behavior. The samples render counters you can increment, a text field you can edit, and a complete-state replacement control.

Start from the project in the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start). Keep its entry file, `StrictMode` wrapper, and stylesheet import; the steps below change the component it mounts.

## Create: update older imports and typings

A store holds state independently of React, and [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) binds it to a hook. For older TypeScript stores, use the curried `create<T>()(initializer)` form instead of supplying separate state, setter, getter, and store type parameters.

1. Use named imports: v5 drops default exports. For a vanilla store, use the named [`createStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#createstore) export from `zustand/vanilla` instead of its older default import.
2. Add `src/migration-store.ts`. [`StateCreator`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#statecreator) types the initializer; [`UseBoundStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#useboundstore) takes a store API type, not the state type alone. [`StoreApi`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storeapi) supplies that type for this store without middleware.

```ts title="src/migration-store.ts"
import { create } from 'zustand'
import type { StateCreator, StoreApi, UseBoundStore } from 'zustand'

export type MigrationState = {
  count: number
  text: string
  increment: () => void
  setText: (text: string) => void
  action?: () => void
}

export const migrationCreator: StateCreator<MigrationState> = (set) => ({
  count: 0,
  text: 'hello',
  increment: () => set((state) => ({ count: state.count + 1 })),
  setText: (text) => set({ text }),
})

export const useMigrationStore: UseBoundStore<StoreApi<MigrationState>> =
  create<MigrationState>()(migrationCreator)
```

3. In the [quick start's counter component](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#3-select-state-and-an-action-in-a-component), replace its store import with `import { useMigrationStore as useCounterStore } from './migration-store'`, keeping the selectors and JSX unchanged: it displays `Count: 0`, and **+1** updates the migrated store while shallow merging preserves its other fields and actions.

4. Keep `Counter` mounted as in the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#4-mount-the-counter). Run `npm run build`, then `npm run dev`.

For older vanilla bindings, let [`useStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#usestore) infer its types from the store and selector. If you supply its first type parameter, supply the **store type**, not the state type. For middleware or slice initializers, `StateCreator<T, Mis, Mos, U>` describes the state, incoming mutators, outgoing mutators, and returned slice. Continue with [Split a store into slices](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/split-store-into-slices) for that composition.

## Migrate to v5 from v4

First update your existing application to the latest v4 release and address its deprecation warnings. Then move to v5. The migration requires React 18 or later and TypeScript 4.5 or later; v5 also drops ES5 and UMD/SystemJS support.

1. Update Zustand and install the React and external-store peer dependencies used by the traditional equality bindings:

```bash
npm install zustand react use-sync-external-store
```

2. Add `src/equality-store.ts`. [`createWithEqualityFn`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-traditional#createwithequalityfn) retains the selector-plus-equality calling pattern. It creates a separate counter here so you can compare the two bindings on screen.

```ts title="src/equality-store.ts"
import { createWithEqualityFn } from 'zustand/traditional'
import { migrationCreator } from './migration-store'
import type { MigrationState } from './migration-store'

export const useEqualityStore =
  createWithEqualityFn<MigrationState>()(migrationCreator)
```

3. Add `src/MigrationPanel.tsx`. The traditional counter selects an object and passes [`shallow`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-shallow#shallow) as the equality argument. The standard counter uses [`useShallow`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-shallow#useshallow) around its object selector instead. Its text field selects a tuple through the same hook.

```tsx title="src/MigrationPanel.tsx"
import { useState } from 'react'
import { shallow, useShallow } from 'zustand/shallow'
import { useEqualityStore } from './equality-store'
import { useMigrationStore } from './migration-store'

const FALLBACK_ACTION = () => window.alert('No action configured')

export default function MigrationPanel() {
  const standard = useMigrationStore(
    useShallow((state) => ({ count: state.count, increment: state.increment })),
  )
  const traditional = useEqualityStore(
    (state) => ({ count: state.count, increment: state.increment }),
    shallow,
  )
  const [text, setText] = useMigrationStore(
    useShallow((state) => [state.text, state.setText] as const),
  )
  const action = useMigrationStore((state) => state.action ?? FALLBACK_ACTION)
  const [replaceFlag, setReplaceFlag] = useState(false)

  function applyState() {
    const completeState = {
      ...useMigrationStore.getState(),
      count: 5,
      text: 'updated',
    }
    const args = [completeState, replaceFlag] as Parameters<
      typeof useMigrationStore.setState
    >
    useMigrationStore.setState(...args)
  }

  return (
    <main style={{ minHeight: 400, display: 'grid', gap: 12 }}>
      <h1>v5 store migration</h1>
      <section>
        <h2>Standard binding</h2>
        <p>Count: {standard.count}</p>
        <button type="button" onClick={standard.increment}>Standard +1</button>
      </section>
      <section>
        <h2>Traditional equality binding</h2>
        <p>Count: {traditional.count}</p>
        <button type="button" onClick={traditional.increment}>Traditional +1</button>
      </section>
      <label>
        Text
        <input value={text} onChange={(event) => setText(event.currentTarget.value)} />
      </label>
      <button type="button" onClick={action}>Run optional action</button>
      <label>
        <input
          type="checkbox"
          checked={replaceFlag}
          onChange={(event) => setReplaceFlag(event.currentTarget.checked)}
        />
        Replace instead of merge
      </label>
      <button type="button" onClick={applyState}>Set count to 5 and update text</button>
    </main>
  )
}
```

4. Change the component import and rendered element in `src/main.tsx` to `MigrationPanel` from `./MigrationPanel.tsx`. Build and run the project again.

![Two counters at zero, the text field containing hello, and the optional-action and replacement controls.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/c71546caf051ee38d834fc2321f5aca1.png)

The page starts with two counters at `0` and the text `hello`. Each increment button changes its own counter. Editing the text updates the standard store. **Run optional action** uses the module-level fallback function when the optional action is absent.

For selectors returning objects or arrays, `useShallow` returns the previous output reference when the top-level contents remain shallowly equal. Keep fallback functions outside the selector so they also retain a reference. See [Select computed state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/select-computed-state) for selector-output pitfalls.

If your existing application binds a vanilla store with custom equality, use [`useStoreWithEqualityFn`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-traditional#usestorewithequalityfn) with the store, selector, and equality function. See [Customize equality checks](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/customize-equality-and-subscriptions) for that binding and equality defaults.

Add these two files to compare vanilla bindings, then update the entry file as described below to mount `VanillaMigrationCounter` in place of `MigrationPanel`. Both displayed counts read the same store: **+1** updates both, while the equality binding compares its object output with `shallow`.

```ts title="src/vanilla-migration-store.ts"
import { createStore } from 'zustand/vanilla'
import { migrationCreator } from './migration-store'
import type { MigrationState } from './migration-store'

export const vanillaMigrationStore =
  createStore<MigrationState>()(migrationCreator)
```

```tsx title="src/VanillaMigrationCounter.tsx"
import { useStore } from 'zustand'
import { useStoreWithEqualityFn } from 'zustand/traditional'
import { shallow } from 'zustand/shallow'
import { vanillaMigrationStore } from './vanilla-migration-store'

export default function VanillaMigrationCounter() {
  const count = useStore(vanillaMigrationStore, (state) => state.count)
  const selected = useStoreWithEqualityFn(
    vanillaMigrationStore,
    (state) => ({ count: state.count, increment: state.increment }),
    shallow,
  )

  return (
    <main style={{ minHeight: 400 }}>
      <h1>Vanilla binding migration</h1>
      <p>Standard count: {count}</p>
      <p>Equality count: {selected.count}</p>
      <button type="button" onClick={selected.increment}>+1</button>
    </main>
  )
}
```

In `src/main.tsx`, replace the `MigrationPanel` import with `import VanillaMigrationCounter from './VanillaMigrationCounter.tsx'` and render `<VanillaMigrationCounter />` instead of `<MigrationPanel />`, keeping the wrapper and stylesheet import from the [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/main.tsx"
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import VanillaMigrationCounter from './VanillaMigrationCounter.tsx'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <VanillaMigrationCounter />
  </StrictMode>,
)
```

### Adapt complete-state replacement

The panel's **Set count to 5 and update text** button supplies a complete state in either mode. With the checkbox unchecked, it merges; with it checked, it replaces. The spread of `getState()` keeps the actions in the supplied complete state, so **Standard +1** still works afterward.

The authors use `Parameters<typeof store.setState>` to pass a dynamic replacement flag. The sample follows that tuple pattern and supplies a complete state so either runtime value is valid. For a literal `true`, the v5 overload requires the complete state directly. See [Type stores and selectors](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) for replacement pitfalls.

| Option or argument | Type | Default | What it does |
| --- | --- | --- | --- |
| Equality argument on a traditional hook | `(a: U, b: U) => boolean` | The factory's default equality function, if supplied | Determines whether the selected output changes; this sample passes `shallow`. |
| `replace` on `setState` | `false` or `true`, with separate overloads | Merge for an object update when omitted | `false` merges the object; `true` replaces the complete state. |

## Adapt persistence initialization

The persistence middleware no longer writes the initial state merely because the store is created. This change applies to v5 and v4.5.5. If your application needs an initial value written to storage, explicitly call `setState` after creation rather than relying on initialization to save it.

Keep the existing counter component and add a persisted variant below. It uses [`persist`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#persist), which ships in Zustand, to restore saved data once during store creation and save subsequent updates.

1. Add `src/persisted-migration-store.ts`. This browser sample saves only `count`, in the middleware's versioned JSON envelope. A failed restore reports the error through `onRehydrateStorage`.

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

type PersistedCounter = {
  count: number
}

export const usePersistedMigrationStore = create<PersistedCounter>()(
  persist(() => ({ count: 0 }), {
    name: 'v5-migration-counter',
    onRehydrateStorage: () => (_state, error) => {
      if (error) console.error('Unable to restore the counter', error)
    },
  }),
)
```

2. Add and mount this component in place of `MigrationPanel`, preserving the entry file's wrapper and stylesheet import.

```tsx title="src/PersistedMigrationCounter.tsx"
import { usePersistedMigrationStore } from './persisted-migration-store'

export default function PersistedMigrationCounter() {
  const count = usePersistedMigrationStore((state) => state.count)

  return (
    <main style={{ minHeight: 400 }}>
      <h1>Persisted migrated counter</h1>
      <p>Count: {count}</p>
      <button
        type="button"
        onClick={() => usePersistedMigrationStore.setState({ count })}
      >
        Save current count
      </button>
      <button
        type="button"
        onClick={() => usePersistedMigrationStore.setState(
          (state) => ({ count: state.count + 1 }),
        )}
      >
        +1 and save
      </button>
      <button
        type="button"
        onClick={() => {
          if (window.confirm('Replace the current count with the saved count?')) {
            void usePersistedMigrationStore.persist.rehydrate()
          }
        }}
      >
        Restore saved count
      </button>
    </main>
  )
}
```

With no saved item, the counter displays `0`. **Save current count** explicitly writes that value; **+1 and save** changes and saves it. Reload to restore the saved count through the middleware's loader, or click **Restore saved count** and confirm. The button calls `rehydrate()` once and asks before replacing current work. Since updates save immediately, restoring normally leaves the count unchanged. Do not overwrite the restored count with a new random value during every startup.

The loader reads the JSON envelope rather than importing executable store code. This round trip retains the counter data, not the component or its behavior:

| Saved content | Kept or lost on restore |
| --- | --- |
| `state.count` | Kept: the default merge copies the saved count into the live state. |
| `version` | Used to check compatibility, not added to the live state. A differing version without a migration function logs an error and does not apply the saved state. |
| Component button handlers and UI | Not saved: JSON storage writes the store data, not the React component. The component defines the controls again on mount. |
| Missing top-level state fields | Kept from the current state by the default shallow merge. |
| Malformed JSON | Not restored: parsing fails and the completion callback reports the error. |

This sample uses synchronous default browser storage, so restoration finishes during creation, before editing begins. For asynchronous storage and explicit restore controls, use [Control state hydration](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/control-persisted-state-hydration). For changes to the saved schema, use [Migrate persisted data](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/migrate-persisted-data); a library-version upgrade is not itself a saved-schema migration.

## Related

- [Type stores and selectors](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) covers current store and replacement typings.
- [Customize equality checks](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/customize-equality-and-subscriptions) covers traditional hooks and custom comparisons.
- [Persist store state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/persist-store-state) covers storage selection and partial persistence.
