Track hydration readiness
Show a loading indicator until persisted state is available.
Zustand · Pipe
onRehydrateStorage lets a persisted Zustand store run logic when storage hydration starts and optionally when it finishes. The completion callback receives the hydrated state and any hydration error.
onRehydrateStorage is a persist option for observing storage hydration. Its outer callback runs before hydration and may return a second callback that receives the resulting state and an optional error when hydration completes.
onRehydrateStorage: (state: Object) => ((state?: Object, error?: Error) => void) | void| Name | Type | Description |
|---|---|---|
state | Object | The store state available to the outer hydration listener. |
state | Object | undefined | The resulting state supplied to the returned callback after hydration; optional. |
error | Error | undefined | An optional hydration error supplied to the returned callback. |
The outer listener may return a callback (state?: Object, error?: Error) => void, or void; the returned callback runs after hydration.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type State = {
ready: boolean
setReady: (ready: boolean) => void
}
export const useStore = create<State>()(
persist(
(set) => ({
ready: false,
setReady: (ready) => set({ ready }),
}),
{
name: 'app-state',
onRehydrateStorage: () => {
console.log('hydration starts')
return (state, error) => {
if (error) console.error('hydration failed', error)
else state?.setReady(true)
}
},
},
),
)The callback runs when hydration begins, and its returned callback runs afterward with the rehydrated state or an error.
Show a loading indicator until persisted state is available.
Record successful hydration or report persistence failures.
Initialize or update a field after persisted values load.
onRehydrateStorage do?It is a persist option whose outer function receives the current state and can return another function. The returned function runs after hydration and receives the resulting state plus an optional error.
Follow-up: How would you detect failed hydration? Inspect the second callback’s error argument; a truthy value indicates that hydration encountered an error.
The outer callback is suitable for work that should happen when hydration starts. Returning a callback lets the store react when hydration finishes, whether successfully or with an error.
Follow-up: How can startup state reflect completion? Update a dedicated field in the returned callback after checking the error argument.
The option observes persistence hydration, while the store’s persisted data is loaded from storage. Rehydration can also be initiated explicitly through the store’s persist.rehydrate() method.
Follow-up: When might explicit rehydration matter? It is useful when hydration should be controlled manually rather than performed automatically during initialization.
persistrehydrateskipHydrationstorage