Evolve a storage schema
Renaming or restructuring persisted fields after a breaking schema change.
Zustand · Pipe
migrate transforms persisted Zustand state when its stored version differs from the configured version. It receives the old state and version, then returns state compatible with the latest schema, synchronously or asynchronously.
Configure persist with a schema version and a migrate function. When the stored version differs from the configured version, the function receives the stored state and its version, then returns state matching the current schema; it may also return a promise for asynchronous migration.
migrate: (persistedState: Object, version: number) => Object | Promise<Object>| Name | Type | Description |
|---|---|---|
persistedState | Object | Previously persisted state to transform. |
version | number | Version number associated with the persisted state. |
Object | Promise<Object>
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type State = { newField: number }
type StoredState = { oldField: number }
export const useStore = create<State>()(
persist(
() => ({ newField: 0 }),
{
name: 'example',
version: 1,
migrate: (persistedState: StoredState, version) => {
if (version === 0) {
return { newField: persistedState.oldField }
}
return persistedState as State
},
},
),
)The persisted schema changes from oldField in version 0 to newField in version 1; the migration converts the old shape before the store uses it.
Renaming or restructuring persisted fields after a breaking schema change.
Converting data written by an older application release into the current state shape.
Performing a migration that requires asynchronous work before hydration completes.
migrate is a persist option with the signature (persistedState: Object, version: number) => Object | Promise<Object>. It receives the stored state and its stored version, and must return data compliant with the version configured in the store.
Follow-up: What happens without migration on a version mismatch? The stored value is not used by default.
Set a new version when the persisted schema changes. When storage and code versions differ, migrate can transform the old state, such as renaming a field, and return the updated object.
Follow-up: How can a migration handle an asynchronous transformation? Return a promise resolving to the state in the latest schema.
The function can branch on the supplied version, apply only the transformations needed for that persisted revision, and return the resulting current state. The documentation demonstrates copying an old field to a new field and deleting the old field.
Follow-up: What contract must every branch satisfy? Every branch must produce state compliant with the latest code version.
persistversionPersist middlewarehydrationstorage