Use custom storage when your persistence engine does not expose the browser Storage API, or when your state needs more than JSON can represent. Connect the engine through persist's storage option: use a string adapter for JSON-backed storage, or a structured-value adapter for your own serialization.
These examples run in the browser, in the project from the React quick start. They display persisted data through mounted React components; reloading the page restores it through persist's automatic hydration rather than a second, manual read.
1. Connect a synchronous string engine
Pass your custom StateStorage engine to createJSONStorage for JSON-backed persistence; see Control state hydration for the storage contract.
The example prefixes keys in sessionStorage. The count survives a page reload in the same tab. Zustand is already installed by the quick start; in another existing React project, install it with:
bashnpm install zustand
Add this store module. create binds the persisted store to the hook used by the counter.
tsimport { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import type { StateStorage } from 'zustand/middleware'
type CounterState = {
count: number
increment: () => void
}
const sessionEngine: StateStorage<void> = {
getItem: (name) => sessionStorage.getItem(`my-app:${name}`),
setItem: (name, value) => sessionStorage.setItem(`my-app:${name}`, value),
removeItem: (name) => sessionStorage.removeItem(`my-app:${name}`),
}
export const useCustomCounter = create<CounterState>()(
persist(
(set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}),
{
name: 'custom-counter',
storage: createJSONStorage(() => sessionEngine),
partialize: (state) => ({ count: state.count }),
version: 1,
onRehydrateStorage: () => (_state, error) => {
if (error) console.error('Counter storage could not be loaded', error)
},
},
),
)
Add the counter component. It subscribes to hydration events as well as the count, so the increment button remains disabled until storage has loaded. This also lets you reuse the component with the asynchronous adapter in the next step.
tsximport { useEffect, useState } from 'react'
import { useCustomCounter } from './custom-counter-store'
export default function CustomCounter() {
const count = useCustomCounter((state) => state.count)
const increment = useCustomCounter((state) => state.increment)
const [hydrated, setHydrated] = useState(
() => useCustomCounter.persist.hasHydrated(),
)
useEffect(() => {
const stopStart = useCustomCounter.persist.onHydrate(() => setHydrated(false))
const stopFinish = useCustomCounter.persist.onFinishHydration(
() => setHydrated(true),
)
setHydrated(useCustomCounter.persist.hasHydrated())
return () => {
stopStart()
stopFinish()
}
}, [])
return (
<section style={{ minHeight: 400 }}>
<h1>Custom storage counter</h1>
<p aria-live="polite">{hydrated ? `Count: ${count}` : 'Loading storage…'}</p>
<button type="button" disabled={!hydrated} onClick={increment}>+1</button>
</section>
)
}
Mount <CustomCounter /> in place of the quick start's counter using the existing entry setup, then run:
bashnpm run build npm run dev
With no saved data, the component displays Count: 0 and a +1 button. Click it, then reload: the stored count appears again. Each action writes the filtered state plus its version; hydration reads that envelope once and merges the count with the store's current action.
2. Connect an asynchronous engine
For IndexedDB, follow the same string contract but return promises. The authors use idb-keyval to adapt its get, set, and del operations to StateStorage.
Install the additional dependency:
bashnpm install idb-keyval
Replace only src/custom-counter-store.ts with this version. The mounted CustomCounter component and entry file stay unchanged.
tsimport { get, set as put, del } from 'idb-keyval'
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import type { StateStorage } from 'zustand/middleware'
type CounterState = {
count: number
increment: () => void
}
const indexedDBEngine: StateStorage<Promise<void>> = {
getItem: async (name) => {
const value: unknown = await get(name)
if (value === undefined || value === null) return null
if (typeof value !== 'string') throw new Error('Expected stored JSON text')
return value
},
setItem: async (name, value) => {
await put(name, value)
},
removeItem: async (name) => {
await del(name)
},
}
export const useCustomCounter = create<CounterState>()(
persist(
(set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}),
{
name: 'indexed-counter',
storage: createJSONStorage(() => indexedDBEngine),
partialize: (state) => ({ count: state.count }),
version: 1,
onRehydrateStorage: () => (_state, error) => {
if (error) console.error('Counter storage could not be loaded', error)
},
},
),
)
The component waits for the IndexedDB read before enabling edits. Increment the counter and reload after the write completes to see the saved count. This is a separate key and engine from the session-storage example; switching adapters does not transfer its saved data.
For loading indicators, hydration failures, and controlled restore timing, continue with Control state hydration.
3. Preserve structured values
Use PersistStorage directly when you want to control serialization. Its methods receive and return a StorageValue envelope containing state and an optional version, not a JSON string. Do not wrap this adapter in createJSONStorage.
The authors use Superjson for Map, Set, Date, and RegExp. This example also validates the decoded envelope with Zod before allowing hydration to use it.
bashnpm install superjson zod
Add a store that persists transaction data, not its action:
tsimport superjson from 'superjson'
import { z } from 'zod'
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { PersistStorage, StorageValue } from 'zustand/middleware'
type TransactionData = {
transactions: Map<string, number>
tags: Set<string>
savedAt: Date
filter: RegExp
}
type TransactionState = TransactionData & {
addTransaction: () => void
}
const envelopeSchema = z.object({
state: z.object({
transactions: z.map(z.string(), z.number()),
tags: z.set(z.string()),
savedAt: z.date(),
filter: z.instanceof(RegExp),
}),
version: z.literal(1),
})
const structuredStorage: PersistStorage<TransactionData, void> = {
getItem: (name) => {
const text = sessionStorage.getItem(name)
if (text === null) return null
return envelopeSchema.parse(superjson.parse(text))
},
setItem: (name, value: StorageValue<TransactionData>) => {
sessionStorage.setItem(name, superjson.stringify(value))
},
removeItem: (name) => sessionStorage.removeItem(name),
}
export const useTransactions = create<TransactionState>()(
persist(
(set) => ({
transactions: new Map([['initial', 10]]),
tags: new Set(['recorded']),
savedAt: new Date('2026-01-01T00:00:00.000Z'),
filter: /^recorded$/i,
addTransaction: () => set((state) => ({
transactions: new Map(state.transactions).set(crypto.randomUUID(), 10),
tags: new Set(state.tags).add('recorded'),
savedAt: new Date(),
})),
}),
{
name: 'structured-transactions',
storage: structuredStorage,
version: 1,
partialize: (state) => ({
transactions: state.transactions,
tags: state.tags,
savedAt: state.savedAt,
filter: state.filter,
}),
onRehydrateStorage: () => (_state, error) => {
if (error) console.error('Transaction storage could not be loaded', error)
},
},
),
)
Add the component. Its display uses the restored objects' methods, not string substitutes for those types.
tsximport { useTransactions } from './structured-store'
export default function StructuredStorage() {
const transactions = useTransactions((state) => state.transactions)
const tags = useTransactions((state) => state.tags)
const savedAt = useTransactions((state) => state.savedAt)
const filter = useTransactions((state) => state.filter)
const addTransaction = useTransactions((state) => state.addTransaction)
return (
<section style={{ minHeight: 400 }}>
<h1>Structured storage</h1>
<p>Transactions: {transactions.size}</p>
<p>Tags: {Array.from(tags).join(', ')}</p>
<p>Saved at: {savedAt.toISOString()}</p>
<p>Filter: {filter.toString()}</p>
<p>Matches recorded: {String(filter.test('recorded'))}</p>
<button type="button" onClick={addTransaction}>Add transaction</button>
</section>
)
}
In src/main.tsx, change the component import to StructuredStorage and render <StructuredStorage />, keeping StrictMode and the stylesheet import. Build and run using the commands from step 1.
With no saved data, you see one transaction, the recorded tag, the initial date, and /^recorded$/i. Add a transaction, then reload in the same tab: the transaction count and updated date return, and the filter still matches recorded. The store creates the action again; the adapter restores only the data.
If decoding or schema validation throws, persist passes the error to the returned onRehydrateStorage callback. This sample logs the failure and keeps the initial state instead of applying the invalid envelope. Its schema accepts version 1 only; use Migrate persisted data when you need to accept and migrate older schemas.
Choose the adapter contract
| Contract | Synchronous read | Asynchronous read | Serialization |
|---|---|---|---|
StateStorage | string or null | Promise<string | null> | Wrap with createJSONStorage; the helper parses and stringifies. |
PersistStorage<S> | StorageValue<S> or null | Promise<StorageValue<S> | null> | Supply the envelope directly; encode, decode, and validate in your adapter if needed. |
Both contracts include setItem and removeItem. Their return type parameter lets an engine return void or, for example, Promise<void>. Use null for a missing key, not an empty string containing no valid JSON.
| Option | Type | Default | What it does |
|---|---|---|---|
name | string | Required | Identifies the store's item; use a unique key. |
storage | PersistStorage<PersistedState> | createJSONStorage(() => window.localStorage) | Chooses the adapter that reads and writes the envelope. |
partialize | (state: S) => PersistedState | Identity function | Selects the data passed to storage. |
version | number | 0 | Marks the persisted schema version; mismatched numeric versions require migration. |
onRehydrateStorage | Before/after hydration callback | Unset | Receives completion or a hydration error through its returned callback. |
createJSONStorage also accepts replacer and reviver functions passed to JSON.stringify and JSON.parse, respectively. Use them for a JSON-specific representation, or use a direct PersistStorage adapter when a serializer already supplies the representation you need.
What survives the round trip
| Value | JSON counter adapter | Structured adapter above |
|---|---|---|
| Selected data | Stores and restores count. | Stores and restores transactions, tags, date, and filter. |
Map, Set, Date, RegExp | Plain JSON does not preserve these as their original types. | Superjson restores their types; the schema checks them. |
| Actions | Excluded by partialize; recreated by the initializer. | Excluded by partialize; recreated by the initializer. |
| Schema version | Stored in the envelope; checked by persist. | Stored in the envelope; checked by the adapter and persist. |
The version is not an integrity checksum. createJSONStorage does not validate the shape of parsed data. Use validation in a direct adapter for data you cannot trust; successful JSON parsing alone does not establish that it matches your state.
Pitfalls and related tasks
createJSONStoragecalls its storage getter when you create the adapter. If the getter throws, it returnsundefined. Keep these browser examples in a client-rendered app; see Server-render React stores for server lifecycles.- Asynchronous loading needs its own UI lifecycle. See Control state hydration rather than triggering another restore after every render.
- For nested persisted objects and schema changes, see Migrate persisted data.
- For immutable updates to collections, see Update Maps and Sets.
URL storage uses the same adapter boundary. Explore the authors' live hash-storage demo and live query-storage demo, then follow Sync state with the URL to implement that task.
Was this page helpful?