Select state and plan persistence migration
Select values, not the entire store
A selector is a function that extracts a value from the store snapshot. Select individual primitives or existing stable references. In Zustand 5, returning a fresh object or array on every evaluation can cause repeated updates or an unstable snapshot error. Shallow equality can stabilize a selection when its immediate fields are unchanged; it does not compare arbitrarily deep structures. Do not mutate nested state to make shallow comparison appear to work.
import React, {useState, useEffect, createContext, useContext} from 'react';import {create, useStore} from 'zustand';import {createStore} from 'zustand/vanilla';import {useShallow} from 'zustand/react/shallow';import {persist, createJSONStorage, subscribeWithSelector, devtools} from 'zustand/middleware';function createPreferences(initial='comfortable') { return createStore((set,get)=>({density:initial, count:0, toggle:()=>set(s=>({density:s.density==='compact'?'comfortable':'compact'})), increment:()=>set(s=>({count:s.count+1})), reset:()=>set({density:initial,count:0}), isCompact:()=>get().density==='compact'}));}const StoreContext=createContext(null);function Scope({children,initial}){ const [store]=useState(()=>createPreferences(initial)); return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;}function usePrefs(selector){const store=useContext(StoreContext);if(!store)throw new Error('Missing Scope');return useStore(store,selector);}function Summary(){const {density,count}=usePrefs(useShallow(s=>({density:s.density,count:s.count})));return <p>{density}, {count} notes</p>;}function Controls(){const add=usePrefs(s=>s.increment);const toggle=usePrefs(s=>s.toggle);return <><button onClick={add}>Add note</button><button onClick={toggle}>Toggle density</button></>;}export default function App(){return <Scope initial="comfortable"><Summary/><Controls/></Scope>;}The summary changes when either selected field changes. The wrapper object may be newly allocated, but shallow comparison can retain the previous equivalent result. Alternatively use two primitive selectors. Do not use useShallow as a promise of zero rerenders: parents, context and React scheduling can still cause rendering. Zustand 4 custom equality patterns should be migrated intentionally; in v5 createWithEqualityFn and useStoreWithEqualityFn from the traditional entry point require the additional peer dependency. This chapter uses the standard Hook and useShallow instead.
Persist only safe preferences
import React, {useState, useEffect, createContext, useContext} from 'react';import {create, useStore} from 'zustand';import {createStore} from 'zustand/vanilla';import {useShallow} from 'zustand/react/shallow';import {persist, createJSONStorage, subscribeWithSelector, devtools} from 'zustand/middleware';function normalizePrefs(raw){ return {density:raw?.density==='compact'?'compact':'comfortable', fontSize:[14,16,18].includes(raw?.fontSize)?raw.fontSize:16};}function migratePrefs(raw,version){ if(version===0)return normalizePrefs({density:raw?.compact===true?'compact':'comfortable',fontSize:raw?.fontSize}); return normalizePrefs(null);}function makeMemoryStorage(){const data=new Map();return {getItem:k=>data.get(k)??null,setItem:(k,v)=>{data.set(k,v);},removeItem:k=>{data.delete(k);}};}function makeStore(){const storage=makeMemoryStorage();storage.setItem('reader-demo',JSON.stringify({state:{compact:true,fontSize:18},version:0})); return createStore(persist(set=>({...normalizePrefs(null),toggle:()=>set(s=>({density:s.density==='compact'?'comfortable':'compact'})),reset:()=>set(normalizePrefs(null))}),{name:'reader-demo',storage:createJSONStorage(()=>storage),version:1,migrate:migratePrefs,partialize:s=>({density:s.density,fontSize:s.fontSize}),merge:(stored,current)=>({...current,...normalizePrefs(stored)}),skipHydration:true}));}export default function App(){const [store]=useState(makeStore);const [status,setStatus]=useState('Defaults');const density=useStore(store,s=>s.density);const font=useStore(store,s=>s.fontSize);return <section><p>{density}, {font}px</p><button onClick={async()=>{try{await store.persist.rehydrate();setStatus(store.persist.hasHydrated()?'Loaded':'Could not load');}catch{setStatus('Could not load');}}}>Load old settings</button><button onClick={()=>{store.getState().reset();setStatus('Reset');}}>Reset settings</button><p role="status">{status}</p></section>;}The fixture starts at comfortable, 16px. Loading version 0 translates the old Boolean compact field into the new density string, and retains the supported font size 18. Reset returns to defaults and writes those preferences; clearing persisted storage is a separate action. The fixture uses a fresh in-memory adapter, so it does not survive a page reload. In a real browser, an approved local storage adapter can persist non-sensitive preferences across sessions, but storage may be unavailable, corrupt or modified. partialize chooses fields, version labels the stored schema, migrate handles a mismatch, and merge controls how recovered values join current state. Validate same-version data too: the custom merge keeps functions and accepts only known values. JSON parse failures and storage errors need a tested recovery policy. Do not persist tokens, passwords or confidential records. SSR must avoid browser-only storage reads during server rendering and keep the first client render consistent; skipHydration allows intentional later hydration.
Observe only the changes that matter
import React, {useState, useEffect, createContext, useContext} from 'react';import {create, useStore} from 'zustand';import {createStore} from 'zustand/vanilla';import {useShallow} from 'zustand/react/shallow';import {persist, createJSONStorage, subscribeWithSelector, devtools} from 'zustand/middleware';function makeStore(){return createStore(subscribeWithSelector(set=>({density:'comfortable',notes:0,toggle:()=>set(s=>({density:s.density==='compact'?'comfortable':'compact'})),add:()=>set(s=>({notes:s.notes+1}))})));}export default function App(){const [store]=useState(makeStore);const [message,setMessage]=useState('No density change');const density=useStore(store,s=>s.density);const notes=useStore(store,s=>s.notes);useEffect(()=>store.subscribe(s=>s.density,(next,previous)=>setMessage(previous+' to '+next)),[store]);return <section><p>{density}, {notes} notes</p><button onClick={()=>store.getState().toggle()}>Toggle</button><button onClick={()=>store.getState().add()}>Add note</button><p role="status">{message}</p></section>;}Adding a note changes the count but leaves the density change message alone. Toggling reports the previous and next value. The middleware enables selector-based subscriptions outside the usual React Hook. Return the unsubscribe function from an Effect so unmount and development cleanup do not leak listeners. The devtools middleware can optionally send actions and state to Redux DevTools; keep it disabled for sensitive environments, use synthetic data and named actions, and clean up connections for disposable stores. It is not a security or audit boundary.
Practice
Predict migration output for compact=true with fontSize=99 and for invalid same-version density. Explain why a shallow merge without validation is not sufficient. Write a subscription test that adds notes, toggles density and unsubscribes.