persist.md
This file
Path
docs/reference/middlewares/persist.md
1,002 lines · 28.0 KiB · Markdown
Last changed by
docs(persist): clarify createJSONStorage behavior and warn about production use (#3541)Copilotbefore adoption038f496
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–33why, one step back1---2title: persist3description: How to persist a store4nav: 285---67# persist89`persist` middleware lets you persist a store's state across page reloads or application10restarts.1112```js13const nextStateCreatorFn = persist(stateCreatorFn, persistOptions)14```1516- [Types](#types)17 - [Signature](#signature)18 - [Mutator](#mutator)19- [Reference](#reference)20- [Usage](#usage)21 - [Persisting a state](#persisting-a-state)22 - [Persisting a state partially](#persisting-a-state-partially)23 - [Persisting a state with custom storage](#persisting-a-state-with-custom-storage)24 - [Persisting a state through versioning and migrations](#persisting-a-state-through-versioning-and-migrations)25 - [Persisting a state with nested objects](#persisting-a-state-with-nested-objects)26 - [Persisting a state and hydrate it manually](#persisting-a-state-and-hydrate-it-manually)27- [Troubleshooting](#troubleshooting)2829## Types3031### Signature3233```tsdocs(persist): add U=T default to persist middleware signature (#3493)Seydi Charyyevbefore adoptionf631347
line 34why, one step back34persist<T, U = T>(stateCreatorFn: StateCreator<T, [], []>, persistOptions: PersistOptions<T, U>): StateCreator<T, [['zustand/persist', U]], []>Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 35–39why, one step back35```3637### Mutator3839```tsUpgrade workflow to use build.yml v3 and deploy-pages v4 (#3393)Danilo Brittobefore adoption49ac892
line 40why, one step back40;['zustand/persist', U]Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 41–44why, one step back41```4243## Reference44docs(persist): fix signature to require persistOptions (#3477)Pavan Shindebefore adoption1b04af1
line 45why, one step back45### `persist(stateCreatorFn, persistOptions)`Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 46–52why, one step back4647#### Parameters4849- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.50 Usually, you will return an object with the methods you want to expose.51- `persistOptions`: An object to define storage options.52 - `name`: A unique name of the item for your store in the storage.docs(persist): clarify createJSONStorage behavior and warn about production use (#3541)Copilotbefore adoption038f496
lines 53–63why, one step back53 - **optional** `storage`: A `PersistStorage` object used to read and write the persisted state.54 Defaults to `createJSONStorage(() => localStorage)`. The getter function passed to55 `createJSONStorage` is evaluated lazily (only when the storage is first accessed), which56 prevents errors in environments where storage APIs like `localStorage` are unavailable at57 module evaluation time — for example, during server-side rendering (SSR).58 > **Warning:** `createJSONStorage` relies on `JSON.parse` and `JSON.stringify` and does not59 > perform any runtime validation. The value read from storage is cast directly to your state60 > type without checking its shape, so corrupt, stale, or tampered data will not be caught at61 > runtime. For production use, implement a custom `PersistStorage` that validates the62 > deserialized value — for example with a schema validation library such as63 > [Zod](https://zod.dev).Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 64–349why, one step back64 - **optional** `partialize`: A function to filter state fields before persisting it.65 - **optional** `onRehydrateStorage`: A function or function returning a function that allows66 custom logic before and after state rehydration.67 - **optional** `version`: A version number for the persisted state. If the stored state version68 doesn't match, it won't be used.69 - **optional** `migrate`: A function to migrate persisted state if the version mismatch occurs.70 - **optional** `merge`: A function for custom logic when merging persisted state with the current71 state during rehydration. Defaults to a shallow merge.72 - **optional** `skipHydration`: Defaults to `false`. If `true`, the middleware won't73 automatically rehydrate the state on initialization. Use `rehydrate` function manually in this74 case. This is useful for server-side rendering (SSR) applications.7576#### Returns7778`persist` returns a state creator function.7980## Usage8182### Persisting a state8384In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`85middleware. The example tracks the `position` of the mouse as it moves within a container and86stores the `position` in local storage, so it persists even when the page reloads.8788We start by setting up a vanilla store that holds the position (an object with `x` and `y`89coordinates) and an action to update it. We'll also use the `persist` middleware to store the90position in `localStorage`.9192```ts93import { createStore } from 'zustand/vanilla'94import { persist } from 'zustand/middleware'9596type PositionStoreState = { position: { x: number; y: number } }9798type PositionStoreActions = {99 setPosition: (nextPosition: PositionStoreState['position']) => void100}101102type PositionStore = PositionStoreState & PositionStoreActions103104const positionStore = createStore<PositionStore>()(105 persist(106 (set) => ({107 position: { x: 0, y: 0 },108 setPosition: (position) => set({ position }),109 }),110 { name: 'position-storage' },111 ),112)113```114115Next, we'll track the mouse movements inside a div and update the store with the new position.116117```ts118const $dotContainer = document.getElementById('dot-container') as HTMLDivElement119const $dot = document.getElementById('dot') as HTMLDivElement120121$dotContainer.addEventListener('pointermove', (event) => {122 positionStore.getState().setPosition({123 x: event.clientX,124 y: event.clientY,125 })126})127```128129We want to reflect the position updates on the screen by moving a div element130(representing the dot) to the new coordinates.131132```ts133const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {134 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`135}136137render(positionStore.getState(), positionStore.getState())138139positionStore.subscribe(render)140```141142Here’s the complete code.143144```ts145import { createStore } from 'zustand/vanilla'146import { persist } from 'zustand/middleware'147148type PositionStoreState = { position: { x: number; y: number } }149150type PositionStoreActions = {151 setPosition: (nextPosition: PositionStoreState['position']) => void152}153154type PositionStore = PositionStoreState & PositionStoreActions155156const positionStore = createStore<PositionStore>()(157 persist(158 (set) => ({159 position: { x: 0, y: 0 },160 setPosition: (position) => set({ position }),161 }),162 { name: 'position-storage' },163 ),164)165166const $dotContainer = document.getElementById('dot-container') as HTMLDivElement167const $dot = document.getElementById('dot') as HTMLDivElement168169$dotContainer.addEventListener('pointermove', (event) => {170 positionStore.getState().setPosition({171 x: event.clientX,172 y: event.clientY,173 })174})175176const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {177 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`178}179180render(positionStore.getState(), positionStore.getState())181182positionStore.subscribe(render)183```184185Here's the `html` code186187```html188<div189 id="dot-container"190 style="position: relative; width: 100vw; height: 100vh;"191>192 <div193 id="dot"194 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"195 ></div>196</div>197```198199### Persisting a state partially200201In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`202middleware. Additionally, we'll show you how to persist only part of the state203(partial persistence), which can be useful when you don’t want to store the entire state in204`localStorage`.205206We’ll first create a vanilla store that holds the position state and actions to update it. We'll207use the `persist` middleware to persist only the relevant part of the state (in this case, the208context containing the position).209210```ts211import { createStore } from 'zustand/vanilla'212import { persist } from 'zustand/middleware'213214type PositionStoreState = {215 context: {216 position: { x: number; y: number }217 }218}219220type PositionStoreActions = {221 actions: {222 setPosition: (223 nextPosition: PositionStoreState['context']['position'],224 ) => void225 }226}227228type PositionStore = PositionStoreState & PositionStoreActions229230const positionStore = createStore<PositionStore>()(231 persist(232 (set) => ({233 context: {234 position: { x: 0, y: 0 },235 },236 actions: {237 setPosition: (position) => set({ context: { position } }),238 },239 }),240 {241 name: 'position-storage',242 partialize: (state) => ({ context: state.context }),243 },244 ),245)246```247248Next, we'll track the mouse movements inside a div and update the store with the new position.249250```ts251const $dotContainer = document.getElementById('dot-container') as HTMLDivElement252const $dot = document.getElementById('dot') as HTMLDivElement253254$dotContainer.addEventListener('pointermove', (event) => {255 positionStore.getState().actions.setPosition({256 x: event.clientX,257 y: event.clientY,258 })259})260```261262We want to reflect the position updates on the screen by moving a div element263(representing the dot) to the new coordinates.264265```ts266const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {267 $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`268}269270render(positionStore.getState(), positionStore.getState())271272positionStore.subscribe(render)273```274275Here’s the full code to create a dot that follows your mouse movement inside a container and276persists the `context` in `localStorage`.277278```ts279import { createStore } from 'zustand/vanilla'280import { persist } from 'zustand/middleware'281282type PositionStoreState = {283 context: {284 position: { x: number; y: number }285 }286}287288type PositionStoreActions = {289 actions: {290 setPosition: (291 nextPosition: PositionStoreState['context']['position'],292 ) => void293 }294}295296type PositionStore = PositionStoreState & PositionStoreActions297298const positionStore = createStore<PositionStore>()(299 persist(300 (set) => ({301 context: {302 position: { x: 0, y: 0 },303 },304 actions: {305 setPosition: (position) => set({ context: { position } }),306 },307 }),308 {309 name: 'position-storage',310 partialize: (state) => ({ context: state.context }),311 },312 ),313)314315const $dotContainer = document.getElementById('dot-container') as HTMLDivElement316const $dot = document.getElementById('dot') as HTMLDivElement317318$dotContainer.addEventListener('pointermove', (event) => {319 positionStore.getState().actions.setPosition({320 x: event.clientX,321 y: event.clientY,322 })323})324325const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {326 $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`327}328329render(positionStore.getState(), positionStore.getState())330331positionStore.subscribe(render)332```333334Here's the `html` code335336```html337<div338 id="dot-container"339 style="position: relative; width: 100vw; height: 100vh;"340>341 <div342 id="dot"343 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"344 ></div>345</div>346```347348### Persisting a state with custom storage349docs(persist): clarify createJSONStorage behavior and warn about production use (#3541)Copilotbefore adoption038f496
lines 350–356why, one step back350> **Note:** `createJSONStorage` is a convenience helper suited for quick prototyping. It uses351> `JSON.parse`/`JSON.stringify` without runtime validation, so unexpected or corrupted data in352> storage is not caught. For production applications, implement a custom `PersistStorage` that353> validates the persisted value, for example using a schema validation library like354> [Zod](https://zod.dev).355356In this mini tutorial, we'll create a simple position-tracking system using vanilla store, whereRevamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 357–1002why, one step back357the position state is persisted in the URL's search parameters. This approach allows state358persistence directly in the browser's URL, which can be useful for maintaining state across page359reloads or sharing links with state embedded.360361We need to implement functions to manipulate URL search parameters as if they were a storage362mechanism. This includes retrieving, setting, and removing parameters.363364```ts365const getSearchParams = () => {366 return new URL(location.href).searchParams367}368369const updateSearchParams = (searchParams: URLSearchParams) => {370 window.history.replaceState(371 {},372 '',373 `${location.pathname}?${searchParams.toString()}`,374 )375}376377const getSearchParam = (key: string) => {378 const searchParams = getSearchParams()379 return searchParams.get(key)380}381382const updateSearchParam = (key: string, value: string) => {383 const searchParams = getSearchParams()384 searchParams.set(key, value)385386 updateSearchParams(searchParams)387}388389const removeSearchParam = (key: string) => {390 const searchParams = getSearchParams()391 searchParams.delete(key)392393 updateSearchParams(searchParams)394}395```396397To use the URL search parameters as storage, we define a `searchParamsStorage` object with398`getItem`, `setItem`, and `removeItem` methods. These methods map to our custom functions that399manipulate search parameters.400401```ts402const searchParamsStorage = {403 getItem: (key: string) => getSearchParam(key),404 setItem: (key: string, value: string) => updateSearchParam(key, value),405 removeItem: (key: string) => removeSearchParam(key),406}407```408409Now, we initialize the vanilla store using the `persist` middleware, specifying that we want to use410our custom storage. Instead of the default `localStorage` or `sessionStorage`, we’ll persist the411position data in the URL search parameters.412413```ts414import { createStore } from 'zustand/vanilla'415import { persist, createJSONStorage } from 'zustand/middleware'416417type PositionStoreState = { position: { x: number; y: number } }418419type PositionStoreActions = {420 setPosition: (nextPosition: PositionStoreState['position']) => void421}422423type PositionStore = PositionStoreState & PositionStoreActions424425const positionStore = createStore<PositionStore>()(426 persist(427 (set) => ({428 position: { x: 0, y: 0 },429 setPosition: (position) => set({ position }),430 }),431 {432 name: 'position-storage',433 storage: createJSONStorage(() => searchParamsStorage),434 },435 ),436)437```438439Next, we'll track the mouse movements inside a div and update the store with the new position.440441```ts442const $dotContainer = document.getElementById('dot-container') as HTMLDivElement443const $dot = document.getElementById('dot') as HTMLDivElement444445$dotContainer.addEventListener('pointermove', (event) => {446 positionStore.getState().setPosition({447 x: event.clientX,448 y: event.clientY,449 })450})451```452453We want to reflect the position updates on the screen by moving a div element454(representing the dot) to the new coordinates.455456```ts457const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {458 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`459}460461render(positionStore.getState(), positionStore.getState())462463positionStore.subscribe(render)464```465466Here’s the full code to create a dot that follows your mouse movement inside a container and467persists the position in URL's search parameters.468469```ts470import { createStore } from 'zustand/vanilla'471import { persist, createJSONStorage } from 'zustand/middleware'472473type PositionStoreState = { position: { x: number; y: number } }474475type PositionStoreActions = {476 setPosition: (nextPosition: PositionStoreState['position']) => void477}478479type PositionStore = PositionStoreState & PositionStoreActions480481const getSearchParams = () => {482 return new URL(location.href).searchParams483}484485const updateSearchParams = (searchParams: URLSearchParams) => {486 window.history.replaceState(487 {},488 '',489 `${location.pathname}?${searchParams.toString()}`,490 )491}492493const getSearchParam = (key: string) => {494 const searchParams = getSearchParams()495 return searchParams.get(key)496}497498const updateSearchParam = (key: string, value: string) => {499 const searchParams = getSearchParams()500 searchParams.set(key, value)501502 updateSearchParams(searchParams)503}504505const removeSearchParam = (key: string) => {506 const searchParams = getSearchParams()507 searchParams.delete(key)508509 updateSearchParams(searchParams)510}511512const searchParamsStorage = {513 getItem: (key: string) => getSearchParam(key),514 setItem: (key: string, value: string) => updateSearchParam(key, value),515 removeItem: (key: string) => removeSearchParam(key),516}517518const positionStore = createStore<PositionStore>()(519 persist(520 (set) => ({521 position: { x: 0, y: 0 },522 setPosition: (position) => set({ position }),523 }),524 {525 name: 'position-storage',526 storage: createJSONStorage(() => searchParamsStorage),527 },528 ),529)530531const $dotContainer = document.getElementById('dot-container') as HTMLDivElement532const $dot = document.getElementById('dot') as HTMLDivElement533534$dotContainer.addEventListener('pointermove', (event) => {535 positionStore.getState().setPosition({536 x: event.clientX,537 y: event.clientY,538 })539})540541const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {542 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`543}544545render(positionStore.getState(), positionStore.getState())546547positionStore.subscribe(render)548```549550Here's the `html` code551552```html553<div554 id="dot-container"555 style="position: relative; width: 100vw; height: 100vh;"556>557 <div558 id="dot"559 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"560 ></div>561</div>562```563564### Persisting a state through versioning and migrations565566In this tutorial, we’ll explore how to manage state persistence using versioning and migration.567We will demonstrate how to evolve your state schema across versions without breaking existing568persisted data.569570Before moving to versioned state management, we simulate an initial state for `version` 0. This is571done by manually setting a `version` 0 state in `localStorage` if it doesn't already exist. The572`version` 0 state saves the coordinates as `x` and `y` fields.573574```ts575// For tutorial purposes only576if (!localStorage.getItem('position-storage')) {577 localStorage.setItem(578 'position-storage',579 JSON.stringify({580 state: { x: 100, y: 100 }, // version 0 structure581 version: 0,582 }),583 )584}585```586587Next, we use `persist` middleware to handle state persistence. We also add a migration function to588handle changes between versions. In this example, we `migrate` the state from `version` 0 (where589`x` and `y` are separate) to `version` 1, where they are combined into a `position` object.590591```ts592migrate: (persisted: any, version) => {593 if (version === 0) {594 persisted.position = { x: persisted.x, y: persisted.y }595 delete persisted.x596 delete persisted.y597 }598599 return persisted600}601```602603Next, we'll track the mouse movements inside a div and update the store with the new position.604605```ts606const $dotContainer = document.getElementById('dot-container') as HTMLDivElement607const $dot = document.getElementById('dot') as HTMLDivElement608609$dotContainer.addEventListener('pointermove', (event) => {610 positionStore.getState().setPosition({611 x: event.clientX,612 y: event.clientY,613 })614})615```616617We want to reflect the position updates on the screen by moving a div element618(representing the dot) to the new coordinates.619620```ts621const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {622 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`623}624625render(positionStore.getState(), positionStore.getState())626627positionStore.subscribe(render)628```629630Here’s the complete code.631632```ts633import { createStore } from 'zustand/vanilla'634import { persist } from 'zustand/middleware'635636// For tutorial purposes only637if (!localStorage.getItem('position-storage')) {638 localStorage.setItem(639 'position-storage',640 JSON.stringify({641 state: { x: 100, y: 100 },642 version: 0,643 }),644 )645}646647type PositionStoreState = { position: { x: number; y: number } }648649type PositionStoreActions = {650 setPosition: (nextPosition: PositionStoreState['position']) => void651}652653type PositionStore = PositionStoreState & PositionStoreActions654655const positionStore = createStore<PositionStore>()(656 persist(657 (set) => ({658 position: { x: 0, y: 0 }, // version 0: just x: 0, y: 0659 setPosition: (position) => set({ position }),660 }),661 {662 name: 'position-storage',663 version: 1,664 migrate: (persisted: any, version) => {665 if (version === 0) {666 persisted.position = { x: persisted.x, y: persisted.y }667 delete persisted.x668 delete persisted.y669 }670671 return persisted672 },673 },674 ),675)676677const $dotContainer = document.getElementById('dot-container') as HTMLDivElement678const $dot = document.getElementById('dot') as HTMLDivElement679680$dotContainer.addEventListener('pointermove', (event) => {681 positionStore.getState().setPosition({682 x: event.clientX,683 y: event.clientY,684 })685})686687const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {688 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`689}690691render(positionStore.getState(), positionStore.getState())692693positionStore.subscribe(render)694```695696Here's the `html` code697698```html699<div700 id="dot-container"701 style="position: relative; width: 100vw; height: 100vh;"702>703 <div704 id="dot"705 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"706 ></div>707</div>708```709710### Persisting a state with nested objects711712In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`713and `y` coordinates. We will also implement persistence using `localStorage` and demonstrate how to714handle merging of state with potentially missing fields.715716To simulate an initial state for the tutorial, we will check if our position data exists in717`localStorage`. If it doesn't, we’ll set it up.718719```ts720if (!localStorage.getItem('position-storage')) {721 localStorage.setItem(722 'position-storage',723 JSON.stringify({724 state: { position: { y: 100 } }, // missing `x` field725 version: 0,726 }),727 )728}729```730731Now, we will create the store and configure it to use persistence and deep merging.732733```ts734import { createStore } from 'zustand/vanilla'735import { persist } from 'zustand/middleware'736import createDeepMerge from '@fastify/deepmerge'737738const deepMerge = createDeepMerge({ all: true })739740type PositionStoreState = { position: { x: number; y: number } }741742type PositionStoreActions = {743 setPosition: (nextPosition: PositionStoreState['position']) => void744}745746type PositionStore = PositionStoreState & PositionStoreActions747748const positionStore = createStore<PositionStore>()(749 persist(750 (set) => ({751 position: { x: 0, y: 0 },752 setPosition: (position) => set({ position }),753 }),754 {755 name: 'position-storage',756 merge: (persisted, current) => deepMerge(current, persisted) as never,757 },758 ),759)760```761762Next, we'll track the mouse movements inside a div and update the store with the new position.763764```ts765const $dotContainer = document.getElementById('dot-container') as HTMLDivElement766const $dot = document.getElementById('dot') as HTMLDivElement767768$dotContainer.addEventListener('pointermove', (event) => {769 positionStore.getState().setPosition({770 x: event.clientX,771 y: event.clientY,772 })773})774```775776We want to reflect the position updates on the screen by moving a div element777(representing the dot) to the new coordinates.778779```ts780const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {781 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`782}783784render(positionStore.getState(), positionStore.getState())785786positionStore.subscribe(render)787```788789Here’s the complete code.790791```ts792import { createStore } from 'zustand/vanilla'793import { persist } from 'zustand/middleware'794import createDeepMerge from '@fastify/deepmerge'795796const deepMerge = createDeepMerge({ all: true })797798// For tutorial purposes only799if (!localStorage.getItem('position-storage')) {800 localStorage.setItem(801 'position-storage',802 JSON.stringify({803 state: { position: { y: 100 } }, // missing `x` field804 version: 0,805 }),806 )807}808809type PositionStoreState = { position: { x: number; y: number } }810811type PositionStoreActions = {812 setPosition: (nextPosition: PositionStoreState['position']) => void813}814815type PositionStore = PositionStoreState & PositionStoreActions816817const positionStore = createStore<PositionStore>()(818 persist(819 (set) => ({820 position: { x: 0, y: 0 },821 setPosition: (position) => set({ position }),822 }),823 {824 name: 'position-storage',825 merge: (persisted, current) => deepMerge(current, persisted) as never,826 },827 ),828)829830const $dotContainer = document.getElementById('dot-container') as HTMLDivElement831const $dot = document.getElementById('dot') as HTMLDivElement832833$dotContainer.addEventListener('pointermove', (event) => {834 positionStore.getState().setPosition({835 x: event.clientX,836 y: event.clientY,837 })838})839840const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {841 console.log({ state })842 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`843}844845render(positionStore.getState(), positionStore.getState())846847positionStore.subscribe(render)848```849850Here's the `html` code851852```html853<div854 id="dot-container"855 style="position: relative; width: 100vw; height: 100vh;"856>857 <div858 id="dot"859 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"860 ></div>861</div>862```863864### Persisting a state and hydrate it manually865866In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`867and `y` coordinates. We will also implement persistence using `localStorage` and explore how to868skip the hydration process and manually trigger rehydration after a delay.869870We start by setting up a vanilla store that holds the position (an object with `x` and `y`871coordinates) and an action to update it. Furthermore, we'll also use the `persist` middleware to872store the position in `localStorage` but skipping hydration.873874```ts875import { createStore } from 'zustand/vanilla'876import { persist } from 'zustand/middleware'877878type PositionStoreState = { position: { x: number; y: number } }879880type PositionStoreActions = {881 setPosition: (nextPosition: PositionStoreState['position']) => void882}883884type PositionStore = PositionStoreState & PositionStoreActions885886const positionStore = createStore<PositionStore>()(887 persist(888 (set) => ({889 position: { x: 0, y: 0 },890 setPosition: (position) => set({ position }),891 }),892 {893 name: 'position-storage',894 skipHydration: true,895 },896 ),897)898```899900Since we skipped hydration in the initial setup, we will manually rehydrate the state. Here, we’re901using `setTimeout` to simulate a delayed rehydration.902903```ts904setTimeout(() => {905 positionStore.persist.rehydrate()906}, 2000)907```908909Next, we'll track the mouse movements inside a div and update the store with the new position.910911```ts912const $dotContainer = document.getElementById('dot-container') as HTMLDivElement913const $dot = document.getElementById('dot') as HTMLDivElement914915$dotContainer.addEventListener('pointermove', (event) => {916 positionStore.getState().setPosition({917 x: event.clientX,918 y: event.clientY,919 })920})921```922923We want to reflect the position updates on the screen by moving a div element924(representing the dot) to the new coordinates.925926```ts927const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {928 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`929}930931render(positionStore.getState(), positionStore.getState())932933positionStore.subscribe(render)934```935936Here’s the complete code.937938```ts939import { createStore } from 'zustand/vanilla'940import { persist } from 'zustand/middleware'941942type PositionStoreState = { position: { x: number; y: number } }943944type PositionStoreActions = {945 setPosition: (nextPosition: PositionStoreState['position']) => void946}947948type PositionStore = PositionStoreState & PositionStoreActions949950const positionStore = createStore<PositionStore>()(951 persist(952 (set) => ({953 position: { x: 0, y: 0 },954 setPosition: (position) => set({ position }),955 }),956 {957 name: 'position-storage',958 skipHydration: true,959 },960 ),961)962963const $dotContainer = document.getElementById('dot-container') as HTMLDivElement964const $dot = document.getElementById('dot') as HTMLDivElement965966$dotContainer.addEventListener('pointermove', (event) => {967 positionStore.getState().setPosition({968 x: event.clientX,969 y: event.clientY,970 })971})972973const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {974 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`975}976977setTimeout(() => {978 positionStore.persist.rehydrate()979}, 2000)980981render(positionStore.getState(), positionStore.getState())982983positionStore.subscribe(render)984```985986Here's the `html` code987988```html989<div990 id="dot-container"991 style="position: relative; width: 100vw; height: 100vh;"992>993 <div994 id="dot"995 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"996 ></div>997</div>998```9991000## Troubleshooting10011002TBD