# Control state hydration

Wait for persisted state before rendering UI that depends on it. Hydration retrieves saved state from storage and merges it with the current store; with asynchronous storage, the initial render still sees the store's defaults.

Use [`persist`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#persist) to save the data and its instance API to decide when to restore it. The example below keeps a bear count in IndexedDB. You first see a restore button, then a loading message while restoration runs, then the restored count and an increment button.

Start from the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start). Keep its entry file, `StrictMode` wrapper, and stylesheet import. These samples run in the browser.

## Persisting a state and hydrate it manually

### 1. Add asynchronous storage

Install Zustand and the IndexedDB helper used by the persistence documentation:

```bash
npm install zustand idb-keyval
```

[`createJSONStorage`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#createjsonstorage) handles JSON serialization and deserialization. Supply an adapter implementing Zustand's [`StateStorage`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#statestorage); its `getItem` returns a promise, making hydration asynchronous.

### 2. Define a store that waits to restore

Add `src/persisted-bear-store.ts`. [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) binds the store to a React hook. `skipHydration: true` prevents the initialization-time storage read; the component triggers it later.

```ts title="src/persisted-bear-store.ts"
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import type { StateStorage } from 'zustand/middleware'
import { del, get, set } from 'idb-keyval'

type BearState = {
  bears: number
  addABear: () => void
}

const storage: StateStorage = {
  getItem: async (name) => {
    const value: string | undefined = await get(name)
    return value ?? null
  },
  setItem: (name, value) => set(name, value),
  removeItem: (name) => del(name),
}

export const useBearStore = create<BearState>()(
  persist(
    (setState) => ({
      bears: 0,
      addABear: () => setState((state) => ({ bears: state.bears + 1 })),
    }),
    {
      name: 'manual-hydration-bears',
      storage: createJSONStorage(() => storage),
      partialize: (state) => ({ bears: state.bears }),
      skipHydration: true,
      onRehydrateStorage: () => {
        console.info('Hydration starts')
        return (_state, error) => {
          if (error !== undefined) {
            console.error('Hydration failed', error)
          } else {
            console.info('Hydration finished')
          }
        }
      },
    },
  ),
)
```

`partialize` saves only `bears`, not the action or hydration UI state. Zustand writes a JSON envelope containing the selected state and a version. Restoration reads that envelope through `rehydrate()` and keeps the action from the current store.

This store uses the default version, `0`, and supplies no migration. If the saved envelope has a different numeric version, Zustand logs a migration error, discards the saved state, and completes hydration with the current defaults. The component then reveals `Bears: 0`, not the restoration-failed alert. To preserve data across schema changes, configure migration as shown in [Migrate persisted data](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/migrate-persisted-data).

`onRehydrateStorage` runs before the read. Its returned callback receives the restored state on success, or an error on failure. Here it reports the lifecycle to the browser console without modifying persisted data.

### 3. Observe hydration and gate the count

Add `src/HydratedBears.tsx`. Subscribe to `onHydrate` and `onFinishHydration` to keep React state synchronized with the hydration lifecycle. Read `hasHydrated()` after subscribing so the component also handles restoration that completed before its effect ran.

```tsx title="src/HydratedBears.tsx"
import { useEffect, useState } from 'react'
import { useBearStore } from './persisted-bear-store'

export default function HydratedBears() {
  const bears = useBearStore((state) => state.bears)
  const addABear = useBearStore((state) => state.addABear)
  const [hydrated, setHydrated] = useState(false)
  const [loading, setLoading] = useState(false)
  const [failed, setFailed] = useState(false)

  useEffect(() => {
    const unsubscribeStart = useBearStore.persist.onHydrate(() => {
      setHydrated(false)
      setLoading(true)
      setFailed(false)
    })
    const unsubscribeFinish = useBearStore.persist.onFinishHydration(() => {
      setHydrated(true)
      setLoading(false)
    })

    setHydrated(useBearStore.persist.hasHydrated())

    return () => {
      unsubscribeStart()
      unsubscribeFinish()
    }
  }, [])

  async function restore() {
    await useBearStore.persist.rehydrate()
    if (!useBearStore.persist.hasHydrated()) {
      setLoading(false)
      setFailed(true)
    }
  }

  return (
    <main style={{ minHeight: 400, display: 'grid', placeContent: 'center', gap: 16 }}>
      <h1>Persisted bears</h1>
      {hydrated ? (
        <>
          <p aria-live="polite">Bears: {bears}</p>
          <button type="button" onClick={addABear}>Add a bear</button>
        </>
      ) : (
        <>
          <p role="status">
            {loading ? 'Restoring saved state…' : 'Saved state has not been restored.'}
          </p>
          {failed && <p role="alert">Restoration failed. Check the console for details.</p>}
          <button type="button" disabled={loading} onClick={() => void restore()}>
            {failed ? 'Retry restoration' : 'Restore saved count'}
          </button>
        </>
      )}
    </main>
  )
}
```

`rehydrate()` starts the storage read. You can `await` it with either synchronous or asynchronous storage; its public return type is `Promise<void> | void`. It does not return the saved state—consume that through the store hook.

Hydration errors reach the `onRehydrateStorage` callback, rather than rejecting the hydration chain. The component therefore checks `hasHydrated()` after awaiting restoration. On failure it keeps the count hidden, displays an alert, and offers a retry. On success the finish listener reveals the count. Both listeners return unsubscribe functions, called when the component unmounts.

### 4. Mount and test the round trip

Keep the [React quick start's mounting setup](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#4-mount-the-counter) and replace `src/Counter.tsx` with this re-export to display the hydration-gated component instead of the counter:

```tsx title="src/Counter.tsx"
export { default } from './HydratedBears'
```

```bash
npm run build
npm run dev
```

Open the local URL printed by Vite:

1. Click **Restore saved count**. If no saved entry exists, successful hydration reveals `Bears: 0`.
2. Click **Add a bear**. The action increments the count and starts writing it to IndexedDB.
3. After that write completes, reload the page. The count stays hidden until you click **Restore saved count**, which reads the saved data once through `rehydrate()`.

The restore control disappears after success, and editing is unavailable before success. This keeps the sample from replacing newer edits with another storage read. The number survives the round trip; the action comes from the store initializer, and the loading and error indicators start fresh with the component.

## Options that control hydration

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `skipHydration` | `boolean` | `false` | `true` leaves initial hydration to your call to `rehydrate()`; `false` starts it during store initialization. |
| `onRehydrateStorage` | `(state: S) => ((state?: S, error?: unknown) => void) \| void` | Unset | Runs before hydration; an optional returned callback handles success or failure. |
| `storage` | `PersistStorage<PersistedState, PersistReturn>` | JSON storage backed by `localStorage` | A promise-returning `getItem` makes the storage read asynchronous. |

The storage type is [`PersistStorage`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#persiststorage). Use `createJSONStorage` to produce it from a string-based storage adapter rather than parsing the payload separately.

## Avoid premature persisted-state assumptions

With asynchronous storage, hydration completes later in a microtask. Do not treat the default state on the first render as the restored state: for example, a default logged-out value does not establish that the saved user is logged out. Gate persisted-value-dependent UI on hydration completion, as the component above does.

`hasHydrated()` is a non-reactive getter, not a subscription. Calling it in JSX alone does not cause a render when hydration finishes. Pair it with lifecycle listeners, or use a reactive store flag updated by `onRehydrateStorage`. `onHydrate` marks the start; `onFinishHydration` marks successful completion, not failure.

For server-rendered applications, continue with [Server-render React stores](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/server-render-react-stores). For nested restored data or schema changes, use [Migrate persisted data](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/migrate-persisted-data).

## Demo and related guides

Explore the [live Zustand demo](https://zustand-demo.pmnd.rs/) for the store-hook and action pattern used here. The [manual-hydration example](https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/persist.md#persisting-a-state-and-hydrate-it-manually) also shows delaying the first call to `rehydrate()`.

- [Persist store state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/persist-store-state) covers persistence setup and choosing saved fields.
- [Implement custom storage](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/implement-custom-storage) covers adapting other storage engines.
