Skip to content
Myr

persisting-store-data.md

This file

Path

docs/reference/integrations/persisting-store-data.md

834 lines · 19.8 KiB · Markdown

Last changed by

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

History of this file

Take it

Show it rendered

1---2title: Persisting store data3nav: 344---56The Persist middleware enables you to store7your Zustand state in a storage8(e.g., `localStorage`, `AsyncStorage`, `IndexedDB`, etc.),9thus persisting its data.1011Note that this middleware supports both12synchronous storages, like `localStorage`,13and asynchronous storages, like `AsyncStorage`,14but using an asynchronous storage does come with a cost.15See [Hydration and asynchronous storages](#hydration-and-asynchronous-storages)16for more details.1718## Simple example1920```ts21import { create } from 'zustand'22import { persist, createJSONStorage } from 'zustand/middleware'2324export const useBearStore = create()(25  persist(26    (set, get) => ({27      bears: 0,28      addABear: () => set({ bears: get().bears + 1 }),29    }),30    {31      name: 'food-storage', // name of the item in the storage (must be unique)32      storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used33    },34  ),35)36```3738## Typescript simple example3940```ts41import { create } from 'zustand'42import { persist, createJSONStorage } from 'zustand/middleware'4344type BearStore = {45  bears: number46  addABear: () => void47}4849export const useBearStore = create<BearStore>()(50  persist(51    (set, get) => ({52      bears: 0,53      addABear: () => set({ bears: get().bears + 1 }),54    }),55    {56      name: 'food-storage', // name of the item in the storage (must be unique)57      storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used58    },59  ),60)61```6263## Options6465### `name`6667This is the only required option.68The given name is going to be the key69used to store your Zustand state in the storage,70so it must be unique.7172### `storage`7374> Type: `() => StateStorage`7576The `StateStorage` can be imported with:7778```ts79import { StateStorage } from 'zustand/middleware'80```8182> Default: `createJSONStorage(() => localStorage)`8384Enables you to use your own storage. Simply pass a function that returns the storage you want to use. It's recommended to use the [`createJSONStorage`](#createjsonstorage) helper function to create a `storage` object that is compliant with the `StateStorage` interface.8586Example:8788```ts89import { persist, createJSONStorage } from 'zustand/middleware'9091export const useBoundStore = create(92  persist(93    (set, get) => ({94      // ...95    }),96    {97      // ...98      storage: createJSONStorage(() => AsyncStorage),99    },100  ),101)102```103104### `partialize`105106> Type: `(state: Object) => Object`107108> Default: `(state) => state`109110Enables you to pick some of the state's fields to be stored in the storage.111112You could omit multiple fields using the following:113114```ts115export const useBoundStore = create(116  persist(117    (set, get) => ({118      foo: 0,119      bar: 1,120    }),121    {122      // ...123      partialize: (state) =>124        Object.fromEntries(125          Object.entries(state).filter(([key]) => !['foo'].includes(key)),126        ),127    },128  ),129)130```131132Or you could allow only specific fields using the following:133134```ts135export const useBoundStore = create(136  persist(137    (set, get) => ({138      foo: 0,139      bar: 1,140    }),141    {142      // ...143      partialize: (state) => ({ foo: state.foo }),144    },145  ),146)147```148149### `onRehydrateStorage`150151> Type: `(state: Object) => ((state?: Object, error?: Error) => void) | void`152153This option enables you to pass a listener function154that will be called when the storage is hydrated.155156Example:157158```ts159export const useBoundStore = create(160  persist(161    (set, get) => ({162      // ...163    }),164    {165      // ...166      onRehydrateStorage: (state) => {167        console.log('hydration starts')168169        // optional170        return (state, error) => {171          if (error) {172            console.log('an error happened during hydration', error)173          } else {174            console.log('hydration finished')175          }176        }177      },178    },179  ),180)181```182183### `version`184185> Type: `number`186187> Default: `0`188189If you want to introduce a breaking change in your storage190(e.g. renaming a field), you can specify a new version number.191By default, if the version in the storage192does not match the version in the code,193the stored value won't be used.194You can use the [migrate](#migrate) function (see below)195to handle breaking changes in order to persist previously stored data.196197### `migrate`198199> Type: `(persistedState: Object, version: number) => Object | Promise<Object>`200201> Default: `(persistedState) => persistedState`202203You can use this option to handle versions migration.204The migrate function takes the persisted state205and the version number as arguments.206It must return a state that is compliant207to the latest version (the version in the code).208209For instance, if you want to rename a field, you can use the following:210211```ts212export const useBoundStore = create(213  persist(214    (set, get) => ({215      newField: 0, // let's say this field was named otherwise in version 0216    }),217    {218      // ...219      version: 1, // a migration will be triggered if the version in the storage mismatches this one220      migrate: (persistedState, version) => {221        if (version === 0) {222          // if the stored value is in version 0, we rename the field to the new name223          persistedState.newField = persistedState.oldField224          delete persistedState.oldField225        }226227        return persistedState228      },229    },230  ),231)232```233234### `merge`235236> Type: `(persistedState: Object, currentState: Object) => Object`237238> Default: `(persistedState, currentState) => ({ ...currentState, ...persistedState })`239240In some cases, you might want to use a custom merge function241to merge the persisted value with the current state.242243By default, the middleware does a shallow merge.244The shallow merge might not be enough245if you have partially persisted nested objects.246For instance, if the storage contains the following:247248```ts249{250  foo: {251    bar: 0,252  }253}254```255256But your Zustand store contains:257258```ts259{260  foo: {261    bar: 0,262    baz: 1,263  }264}265```266267The shallow merge will erase the `baz` field from the `foo` object.268One way to fix this would be to give a custom deep merge function:269270```ts271export const useBoundStore = create(272  persist(273    (set, get) => ({274      foo: {275        bar: 0,276        baz: 1,277      },278    }),279    {280      // ...281      merge: (persistedState, currentState) =>282        deepMerge(currentState, persistedState),283    },284  ),285)286```287288### `skipHydration`289290> Type: `boolean | undefined`291292> Default: `undefined`293294By default the store will be hydrated on initialization.295296In some applications you may need to control when the first hydration occurs.297For example, in server-rendered apps.298299If you set `skipHydration`, the initial call for hydration isn't called,300and it is left up to you to manually call `rehydrate()`.301302```ts303export const useBoundStore = create(304  persist(305    () => ({306      count: 0,307      // ...308    }),309    {310      // ...311      skipHydration: true,312    },313  ),314)315```316317```tsx318import { useBoundStore } from './path-to-store';319320export function StoreConsumer() {321  // hydrate persisted store after on mount322  useEffect(() => {323    useBoundStore.persist.rehydrate();324  }, [])325326  return (327    //...328  )329}330```331332## API333334> Version: >=3.6.3335336The Persist API enables you to do a number of interactions337with the Persist middleware338from inside or outside of a React component.339340### `getOptions`341342> Type: `() => Partial<PersistOptions>`343344> Returns: Options of the Persist middleware345346For example, it can be used to obtain the storage name:347348```ts349useBoundStore.persist.getOptions().name350```351352### `setOptions`353354> Type: `(newOptions: Partial<PersistOptions>) => void`355356Changes the middleware options.357Note that the new options will be merged with the current ones.358359For instance, this can be used to change the storage name:360361```ts362useBoundStore.persist.setOptions({363  name: 'new-name',364})365```366367Or even to change the storage engine:368369```ts370useBoundStore.persist.setOptions({371  storage: createJSONStorage(() => sessionStorage),372})373```374375### `clearStorage`376377> Type: `() => void`378379Clears everything stored under the [name](#name) key.380381```ts382useBoundStore.persist.clearStorage()383```384385### `rehydrate`386387> Type: `() => Promise<void>`388389In some cases, you might want to trigger the rehydration manually.390This can be done by calling the `rehydrate` method.391392```ts393await useBoundStore.persist.rehydrate()394```395396### `hasHydrated`397398> Type: `() => boolean`399400This is a non-reactive getter to check401if the storage has been hydrated402(note that it updates when calling [`rehydrate`](#rehydrate)).403404```ts405useBoundStore.persist.hasHydrated()406```407408### `onHydrate`409410> Type: `(listener: (state) => void) => () => void`411412> Returns: Unsubscribe function413414This listener will be called when the hydration process starts.415416```ts417const unsub = useBoundStore.persist.onHydrate((state) => {418  console.log('hydration starts')419})420421// later on...422unsub()423```424425### `onFinishHydration`426427> Type: `(listener: (state) => void) => () => void`428429> Returns: Unsubscribe function430431This listener will be called when the hydration process ends.432433```ts434const unsub = useBoundStore.persist.onFinishHydration((state) => {435  console.log('hydration finished')436})437438// later on...439unsub()440```441442### `createJSONStorage`443444> Type: `(getStorage: () => StateStorage, options?: JsonStorageOptions) => StateStorage`445446> Returns: `PersistStorage`447448This helper function enables you to create a [`storage`](#storage) object which is useful when you want to use a custom storage engine.449450`getStorage` is a function that returns the storage engine with the properties `getItem`, `setItem`, and `removeItem`.451452`options` is an optional object that can be used to customize the serialization and deserialization of the data. `options.reviver` is a function that is passed to `JSON.parse` to deserialize the data. `options.replacer` is a function that is passed to `JSON.stringify` to serialize the data.453454```ts455import { createJSONStorage } from 'zustand/middleware'456457const storage = createJSONStorage(() => sessionStorage, {458  reviver: (key, value) => {459    if (value && value.type === 'date') {460      return new Date(value)461    }462    return value463  },464  replacer: (key, value) => {465    // NOTE: the result of `.toJSON()` is passed to the466    // replacer function as value if is available so467    // a Date is always a `string` at this point468    if (key === 'someDate') return { type: 'date', value }469    return value470  },471})472```473474## Hydration and asynchronous storages475476To explain what is the "cost" of asynchronous storages,477you need to understand what is hydration.478479In a nutshell, hydration is a process480of retrieving persisted state from the storage481and merging it with the current state.482483The Persist middleware does two kinds of hydration:484synchronous and asynchronous.485If the given storage is synchronous (e.g., `localStorage`),486hydration will be done synchronously.487On the other hand, if the given storage is asynchronous (e.g., `AsyncStorage`),488hydration will be done asynchronously (shocking, I know!).489490But what's the catch?491With synchronous hydration,492the Zustand store will already have been hydrated at its creation.493In contrast, with asynchronous hydration,494the Zustand store will be hydrated later on, in a microtask.495496Why does it matter?497Asynchronous hydration can cause some unexpected behaviors.498For instance, if you use Zustand in a React app,499the store will **not** be hydrated at the initial render.500In cases where your app depends on the persisted value at page load,501you might want to wait until502the store has been hydrated before showing anything.503For example, your app might think the user504is not logged in because it's the default,505but in reality the store has not been hydrated yet.506507If your app does depends on the persisted state at page load,508see [_How can I check if my store has been hydrated_](#how-can-i-check-if-my-store-has-been-hydrated)509in the [FAQ](#faq) section below.510511### Usage in Next.js512513NextJS uses Server Side Rendering, and it will compare the rendered component on the server with the one rendered on client.514But since you are using data from browser to change your component, the two renders will differ and Next will throw a warning at you.515516The errors usually are:517518- Text content does not match server-rendered HTML519- Hydration failed because the initial UI does not match what was rendered on the server520- There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering521522To solve these errors, create a custom hook so that Zustand waits a little before changing your components.523524Create a file with the following:525526```ts527// useStore.ts528import { useState, useEffect } from 'react'529530const useStore = <T, F>(531  store: (callback: (state: T) => unknown) => unknown,532  callback: (state: T) => F,533) => {534  const result = store(callback) as F535  const [data, setData] = useState<F>()536537  useEffect(() => {538    setData(result)539  }, [result])540541  return data542}543544export default useStore545```546547Now in your pages, you will use the hook a little bit differently:548549```ts550// useBearStore.ts551552import { create } from 'zustand'553import { persist } from 'zustand/middleware'554555// the store itself does not need any change556export const useBearStore = create(557  persist(558    (set, get) => ({559      bears: 0,560      addABear: () => set({ bears: get().bears + 1 }),561    }),562    {563      name: 'food-storage',564    },565  ),566)567```568569```ts570// yourComponent.tsx571572import useStore from './useStore'573import { useBearStore } from './stores/useBearStore'574575const bears = useStore(useBearStore, (state) => state.bears)576```577578Credits: [This reply to an issue](https://github.com/pmndrs/zustand/issues/938#issuecomment-1481801942), which points to [this blog post](https://dev.to/abdulsamad/how-to-use-zustands-persist-middleware-in-nextjs-4lb5).579580## FAQ581582### How can I check if my store has been hydrated583584There are a few different ways to do this.585586You can use the [`onRehydrateStorage`](#onrehydratestorage)587listener function to update a field in the store:588589```ts590const useBoundStore = create(591  persist(592    (set, get) => ({593      // ...594      _hasHydrated: false,595      setHasHydrated: (state) => {596        set({597          _hasHydrated: state598        });599      }600    }),601    {602      // ...603      onRehydrateStorage: (state) => {604        return () => state.setHasHydrated(true)605      }606    }607  )608);609610export default function App() {611  const hasHydrated = useBoundStore(state => state._hasHydrated);612613  if (!hasHydrated) {614    return <p>Loading...</p>615  }616617  return (618    // ...619  );620}621```622623You can also create a custom `useHydration` hook:624625```ts626const useBoundStore = create(persist(...))627628const useHydration = () => {629  const [hydrated, setHydrated] = useState(false)630631  useEffect(() => {632    // Note: This is just in case you want to take into account manual rehydration.633    // You can remove the following line if you don't need it.634    const unsubHydrate = useBoundStore.persist.onHydrate(() => setHydrated(false))635636    const unsubFinishHydration = useBoundStore.persist.onFinishHydration(() => setHydrated(true))637638    setHydrated(useBoundStore.persist.hasHydrated())639640    return () => {641      unsubHydrate()642      unsubFinishHydration()643    }644  }, [])645646  return hydrated647}648```649650### How can I use a custom storage engine651652If the storage you want to use does not match the expected API, you can create your own storage:653654```ts655import { create } from 'zustand'656import { persist, createJSONStorage, StateStorage } from 'zustand/middleware'657import { get, set, del } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.658659// Custom storage object660const storage: StateStorage = {661  getItem: async (name: string): Promise<string | null> => {662    console.log(name, 'has been retrieved')663    return (await get(name)) || null664  },665  setItem: async (name: string, value: string): Promise<void> => {666    console.log(name, 'with value', value, 'has been saved')667    await set(name, value)668  },669  removeItem: async (name: string): Promise<void> => {670    console.log(name, 'has been deleted')671    await del(name)672  },673}674675export const useBoundStore = create(676  persist(677    (set, get) => ({678      bears: 0,679      addABear: () => set({ bears: get().bears + 1 }),680    }),681    {682      name: 'food-storage', // unique name683      storage: createJSONStorage(() => storage),684    },685  ),686)687```688689If you're using a type that `JSON.stringify()` doesn't support, you'll need to write your own serialization/deserialization code. However, if this is tedious, you can use third-party libraries to serialize and deserialize different types of data.690691For example, [Superjson](https://github.com/blitz-js/superjson) can serialize data along with its type, allowing the data to be parsed back to its original type upon deserialization692693```ts694import superjson from 'superjson' //  can use anything: serialize-javascript, devalue, etc.695import { PersistStorage } from 'zustand/middleware'696697interface BearState {698  bear: Map<string, string>699  fish: Set<string>700  time: Date701  query: RegExp702}703704const storage: PersistStorage<BearState> = {705  getItem: (name) => {706    const str = localStorage.getItem(name)707    if (!str) return null708    return superjson.parse(str)709  },710  setItem: (name, value) => {711    localStorage.setItem(name, superjson.stringify(value))712  },713  removeItem: (name) => localStorage.removeItem(name),714}715716const initialState: BearState = {717  bear: new Map(),718  fish: new Set(),719  time: new Date(),720  query: new RegExp(''),721}722723export const useBearStore = create<BearState>()(724  persist(725    (set) => ({726      ...initialState,727      // ...728    }),729    {730      name: 'food-storage',731      storage,732    },733  ),734)735```736737### How can I rehydrate on storage event738739You can use the Persist API to create your own implementation,740similar to the example below:741742```ts743type StoreWithPersist = Mutate<StoreApi<State>, [["zustand/persist", unknown]]>744745export const withStorageDOMEvents = (store: StoreWithPersist) => {746  const storageEventCallback = (e: StorageEvent) => {747    if (e.key === store.persist.getOptions().name && e.newValue) {748      store.persist.rehydrate()749    }750  }751752  window.addEventListener('storage', storageEventCallback)753754  return () => {755    window.removeEventListener('storage', storageEventCallback)756  }757}758759const useBoundStore = create(persist(...))760withStorageDOMEvents(useBoundStore)761```762763### How do I use it with TypeScript764765Basic typescript usage doesn't require anything special766except for writing `create<State>()(...)` instead of `create(...)`.767768```tsx769import { create } from 'zustand'770import { persist, createJSONStorage } from 'zustand/middleware'771772interface MyState {773  bears: number774  addABear: () => void775}776777export const useBearStore = create<MyState>()(778  persist(779    (set, get) => ({780      bears: 0,781      addABear: () => set({ bears: get().bears + 1 }),782    }),783    {784      name: 'food-storage', // name of item in the storage (must be unique)785      storage: createJSONStorage(() => sessionStorage), // (optional) by default the 'localStorage' is used786      partialize: (state) => ({ bears: state.bears }),787    },788  ),789)790```791792### How do I use it with Map and Set793794In order to persist object types such as `Map` and `Set`, they will need to be converted to JSON-serializable types such as an `Array` which can be done by defining a custom `storage` engine.795796Let's say your state uses `Map` to handle a list of `transactions`,797then you can convert the `Map` into an `Array` in the `storage` prop which is shown below:798799```ts800801interface BearState {802  .803  .804  .805  transactions: Map<any>806}807808  storage: {809    getItem: (name) => {810      const str = localStorage.getItem(name);811      if (!str) return null;812      const existingValue = JSON.parse(str);813      return {814        ...existingValue,815        state: {816          ...existingValue.state,817          transactions: new Map(existingValue.state.transactions),818        }819      }820    },821    setItem: (name, newValue: StorageValue<BearState>) => {822      // functions cannot be JSON encoded823      const str = JSON.stringify({824        ...newValue,825        state: {826          ...newValue.state,827          transactions: Array.from(newValue.state.transactions.entries()),828        },829      })830      localStorage.setItem(name, str)831    },832    removeItem: (name) => localStorage.removeItem(name),833  },834```