Zustand persist: version bump, migrate, and merge behavior for evolving nested state
0 reputation · 17 Oct 2021, 22:25 UTC
Configuration goal
I have a Zustand store using the persist middleware (default localStorage via createJSONStorage) with version: 1. The state shape is changing: a nested preferences object is gaining new fields with defaults, and one old field is being renamed. I need existing users' persisted snapshots to keep working after the update.
Constraints and uncertainty
The docs describe a migrate function that runs when the persisted version differs from the configured version, and a merge option that controls how rehydrated state combines with current state. What is unclear to me is the interaction between the two: after migrate returns an updated snapshot, does the default shallow merge then overwrite my newly added nested defaults with the old nested object, dropping the new fields? I also need to know what happens to snapshots whose version has no matching migration path — whether they are discarded silently or trigger an error I can handle via onRehydrateStorage.
Assume zustand v4/v5; option signatures have changed across majors, so answers should note version assumptions.
Questions
- Should
migratereturn a fully complete state, or is a custom deepmergefunction required to preserve new nested defaults? - How can I detect and log discarded snapshots (version mismatch with no migration) instead of losing them silently?
- Does
partializeinteract with migration if the renamed field was previously excluded from storage?