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. 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 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.
- Use named imports: v5 drops default exports. For a vanilla store, use the named
createStoreexport fromzustand/vanillainstead of its older default import. - Add
src/migration-store.ts.StateCreatortypes the initializer;UseBoundStoretakes a store API type, not the state type alone.StoreApisupplies that type for this store without middleware.
tsimport { 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)
-
In the quick start's counter component, replace its store import with
import { useMigrationStore as useCounterStore } from './migration-store', keeping the selectors and JSX unchanged: it displaysCount: 0, and +1 updates the migrated store while shallow merging preserves its other fields and actions. -
Keep
Countermounted as in the React quick start. Runnpm run build, thennpm run dev.
For older vanilla bindings, let 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 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.
- Update Zustand and install the React and external-store peer dependencies used by the traditional equality bindings:
bashnpm install zustand react use-sync-external-store
- Add
src/equality-store.ts.createWithEqualityFnretains the selector-plus-equality calling pattern. It creates a separate counter here so you can compare the two bindings on screen.
tsimport { createWithEqualityFn } from 'zustand/traditional'
import { migrationCreator } from './migration-store'
import type { MigrationState } from './migration-store'
export const useEqualityStore =
createWithEqualityFn<MigrationState>()(migrationCreator)
- Add
src/MigrationPanel.tsx. The traditional counter selects an object and passesshallowas the equality argument. The standard counter usesuseShallowaround its object selector instead. Its text field selects a tuple through the same hook.
tsximport { 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>
)
}
- Change the component import and rendered element in
src/main.tsxtoMigrationPanelfrom./MigrationPanel.tsx. Build and run the project again.
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 for selector-output pitfalls.
If your existing application binds a vanilla store with custom equality, use useStoreWithEqualityFn with the store, selector, and equality function. See Customize equality checks 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.
tsimport { createStore } from 'zustand/vanilla'
import { migrationCreator } from './migration-store'
import type { MigrationState } from './migration-store'
export const vanillaMigrationStore =
createStore<MigrationState>()(migrationCreator)
tsximport { 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.
tsximport { 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 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, which ships in Zustand, to restore saved data once during store creation and save subsequent updates.
- Add
src/persisted-migration-store.ts. This browser sample saves onlycount, in the middleware's versioned JSON envelope. A failed restore reports the error throughonRehydrateStorage.
tsimport { 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)
},
}),
)
- Add and mount this component in place of
MigrationPanel, preserving the entry file's wrapper and stylesheet import.
tsximport { 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. For changes to the saved schema, use Migrate persisted data; a library-version upgrade is not itself a saved-schema migration.
Related
- Type stores and selectors covers current store and replacement typings.
- Customize equality checks covers traditional hooks and custom comparisons.
- Persist store state covers storage selection and partial persistence.
Was this page helpful?