Restore persisted client state
A browser app restores user preferences or session-related UI state after a reload.
Zustand · Const
Persist rehydration retrieves saved state from storage and merges it with the current Zustand state. It can happen automatically or be triggered manually through the persist API.
The persist middleware reads saved state from its configured storage and combines it with the current store state. Rehydration is synchronous for synchronous storage and asynchronous for asynchronous storage; setting skipHydration prevents automatic rehydration so the store can call persist.rehydrate() explicitly.
await useBoundStore.persist.rehydrate()| Name | Type | Description |
|---|---|---|
options | PersistOptions | The persist configuration; rehydration-related options include skipHydration, onRehydrateStorage, and storage. |
rehydrate(): Promise<void>
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type State = {
count: number
increment: () => void
}
export const useStore = create<State>()(
persist(
(set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}),
{ name: 'counter-storage', skipHydration: true },
),
)
await useStore.persist.rehydrate()
const hydrated = useStore.persist.hasHydrated()This creates a persisted store, disables automatic initialization rehydration, then explicitly rehydrates it and checks whether hydration has completed.
A browser app restores user preferences or session-related UI state after a reload.
An SSR application needs to avoid restoring browser storage during initial store creation.
An application uses asynchronous storage and must know when saved state becomes available.
A UI needs to display a loading state until persisted values have been restored.
Rehydration retrieves persisted data from storage and merges it into the current Zustand state. Synchronous storage completes this during store creation, while asynchronous storage completes later in a microtask.
Follow-up: How would you prevent automatic rehydration during SSR? Set skipHydration to true, then call the persist API's rehydrate method at a controlled client-side point.
The rehydrate method manually starts restoration and returns a Promise<void>. It is useful when automatic initialization rehydration is disabled or when restoration must occur at a chosen time.
Follow-up: How can code observe completion? Supply onRehydrateStorage for lifecycle callbacks, or inspect hasHydrated() after rehydration.
Synchronous storage, such as localStorage, hydrates while the store is created. Asynchronous storage, such as AsyncStorage, hydrates afterward, so initial reads can see the default state first.
Follow-up: What UI issue can this create? Rendering persisted values before asynchronous hydration finishes can produce inconsistent initial output; gate that rendering on hydration state.
persistonRehydrateStorageskipHydrationhasHydratedstoragecreateJSONStorage