Skip to content
Myr

Revamping docs - file restructuring (#3392)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat: file restructuring * feat: update docs gh workflow * feat: update docs order * feat: update docs * feat: clean up * feat: fix linting * feat: moving config files to rspress theme config

authored by Danilo Britto · committed by GitHub · parent 9c6dff7 · Browse files · 87 files+13307 added−13219 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

87 files+13307 added−13219 removed

  • other:+13307 added−13219 removed

87 files+13307 added−13219 removed

modified:.github/workflows/docs.yml+3 added-3 removed
deleted:docs/apis/create-store.md-517 removed
1---2title: createStore3description: How to create vanilla stores4nav: 245---67`createStore` lets you create a vanilla store that exposes API utilities.89```js10const someStore = createStore(stateCreatorFn)11```1213- [Types](#types)14 - [Signature](#signature)15- [Reference](#reference)16- [Usage](#usage)17 - [Updating state based on previous state](#updating-state-based-on-previous-state)18 - [Updating Primitives in State](#updating-primitives-in-state)19 - [Updating Objects in State](#updating-objects-in-state)20 - [Updating Arrays in State](#updating-arrays-in-state)21 - [Subscribing to state updates](#subscribing-to-state-updates)22- [Troubleshooting](#troubleshooting)23 - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)2425## Types2627### Signature2829```ts30createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>31```3233## Reference3435### `createStore(stateCreatorFn)`3637#### Parameters3839- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.40 Usually, you will return an object with the methods you want to expose.4142#### Returns4344`createStore` returns a vanilla store that exposes API utilities, `setState`, `getState`,45`getInitialState` and `subscribe`.4647## Usage4849### Updating state based on previous state5051This example shows how you can support **updater functions** within **actions**.5253```tsx54import { createStore } from 'zustand/vanilla'5556type AgeStoreState = { age: number }5758type AgeStoreActions = {59 setAge: (60 nextAge:61 | AgeStoreState['age']62 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),63 ) => void64}6566type AgeStore = AgeStoreState & AgeStoreActions6768const ageStore = createStore<AgeStore>()((set) => ({69 age: 42,70 setAge: (nextAge) =>71 set((state) => ({72 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,73 })),74}))7576function increment() {77 ageStore.getState().setAge((currentAge) => currentAge + 1)78}7980const $yourAgeHeading = document.getElementById(81 'your-age',82) as HTMLHeadingElement83const $incrementBy3Button = document.getElementById(84 'increment-by-3',85) as HTMLButtonElement86const $incrementBy1Button = document.getElementById(87 'increment-by-1',88) as HTMLButtonElement8990$incrementBy3Button.addEventListener('click', () => {91 increment()92 increment()93 increment()94})9596$incrementBy1Button.addEventListener('click', () => {97 increment()98})99100const render: Parameters<typeof ageStore.subscribe>[0] = (state) => {101 $yourAgeHeading.innerHTML = `Your age: ${state.age}`102}103104render(ageStore.getInitialState(), ageStore.getInitialState())105106ageStore.subscribe(render)107```108109Here's the `html` code110111```html112<h1 id="your-age"></h1>113<button id="increment-by-3" type="button">+3</button>114<button id="increment-by-1" type="button">+1</button>115```116117### Updating Primitives in State118119State can hold any kind of JavaScript value. When you want to update built-in primitive values like120numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied121correctly, and avoid unexpected behaviors.122123> [!NOTE]124> By default, `set` function performs a shallow merge. If you need to completely replace125> the state with a new one, use the `replace` parameter set to `true`126127```ts128import { createStore } from 'zustand/vanilla'129130type XStore = number131132const xStore = createStore<XStore>()(() => 0)133134const $dotContainer = document.getElementById('dot-container') as HTMLDivElement135const $dot = document.getElementById('dot') as HTMLDivElement136137$dotContainer.addEventListener('pointermove', (event) => {138 xStore.setState(event.clientX, true)139})140141const render: Parameters<typeof xStore.subscribe>[0] = (x) => {142 $dot.style.transform = `translate(${x}px, 0)`143}144145render(xStore.getInitialState(), xStore.getInitialState())146147xStore.subscribe(render)148```149150Here's the `html` code151152```html153<div154 id="dot-container"155 style="position: relative; width: 100vw; height: 100vh;"156>157 <div158 id="dot"159 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"160 ></div>161</div>162```163164### Updating Objects in State165166Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store167them in state. Instead, when you want to update an object, you need to create a new one (or make a168copy of an existing one), and then set the state to use the new object.169170By default, `set` function performs a shallow merge. For most updates where you only need to modify171specific properties, the default shallow merge is preferred as it's more efficient. To completely172replace the state with a new one, use the `replace` parameter set to `true` with caution, as it173discards any existing nested data within the state.174175```ts176import { createStore } from 'zustand/vanilla'177178type PositionStoreState = { position: { x: number; y: number } }179180type PositionStoreActions = {181 setPosition: (nextPosition: PositionStoreState['position']) => void182}183184type PositionStore = PositionStoreState & PositionStoreActions185186const positionStore = createStore<PositionStore>()((set) => ({187 position: { x: 0, y: 0 },188 setPosition: (position) => set({ position }),189}))190191const $dotContainer = document.getElementById('dot-container') as HTMLDivElement192const $dot = document.getElementById('dot') as HTMLDivElement193194$dotContainer.addEventListener('pointermove', (event) => {195 positionStore.getState().setPosition({196 x: event.clientX,197 y: event.clientY,198 })199})200201const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {202 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`203}204205render(positionStore.getInitialState(), positionStore.getInitialState())206207positionStore.subscribe(render)208```209210Here's the `html` code211212```html213<div214 id="dot-container"215 style="position: relative; width: 100vw; height: 100vh;"216>217 <div218 id="dot"219 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"220 ></div>221</div>222```223224### Updating Arrays in State225226Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in227state. Just like with objects, when you want to update an array stored in state, you need to create228a new one (or make a copy of an existing one), and then set state to use the new array.229230By default, `set` function performs a shallow merge. To update array values we should assign new231values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely232replace the state with a new one, use the `replace` parameter set to `true`.233234> [!IMPORTANT]235> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,236> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid237> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,238> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.239240```ts241import { createStore } from 'zustand/vanilla'242243type PositionStore = [number, number]244245const positionStore = createStore<PositionStore>()(() => [0, 0])246247const $dotContainer = document.getElementById('dot-container') as HTMLDivElement248const $dot = document.getElementById('dot') as HTMLDivElement249250$dotContainer.addEventListener('pointermove', (event) => {251 positionStore.setState([event.clientX, event.clientY], true)252})253254const render: Parameters<typeof positionStore.subscribe>[0] = ([x, y]) => {255 $dot.style.transform = `translate(${x}px, ${y}px)`256}257258render(positionStore.getInitialState(), positionStore.getInitialState())259260positionStore.subscribe(render)261```262263Here's the `html` code264265```html266<div267 id="dot-container"268 style="position: relative; width: 100vw; height: 100vh;"269>270 <div271 id="dot"272 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"273 ></div>274</div>275```276277### Subscribing to state updates278279By subscribing to state updates, you register a callback that fires whenever the store's state280updates. We can use `subscribe` for external state management.281282```ts283import { createStore } from 'zustand/vanilla'284285type PositionStoreState = { position: { x: number; y: number } }286287type PositionStoreActions = {288 setPosition: (nextPosition: PositionStoreState['position']) => void289}290291type PositionStore = PositionStoreState & PositionStoreActions292293const positionStore = createStore<PositionStore>()((set) => ({294 position: { x: 0, y: 0 },295 setPosition: (position) => set({ position }),296}))297298const $dot = document.getElementById('dot') as HTMLDivElement299300$dot.addEventListener('mouseenter', (event) => {301 const parent = event.currentTarget.parentElement302 const parentWidth = parent.clientWidth303 const parentHeight = parent.clientHeight304305 positionStore.getState().setPosition({306 x: Math.ceil(Math.random() * parentWidth),307 y: Math.ceil(Math.random() * parentHeight),308 })309})310311const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {312 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`313}314315render(positionStore.getInitialState(), positionStore.getInitialState())316317positionStore.subscribe(render)318319const logger: Parameters<typeof positionStore.subscribe>[0] = (state) => {320 console.log('new position', { position: state.position })321}322323positionStore.subscribe(logger)324```325326Here's the `html` code327328```html329<div330 id="dot-container"331 style="position: relative; width: 100vw; height: 100vh;"332>333 <div334 id="dot"335 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"336 ></div>337</div>338```339340## Troubleshooting341342### I’ve updated the state, but the screen doesn’t update343344In the previous example, the `position` object is always created fresh from the current cursor345position. But often, you will want to include existing data as a part of the new object you’re346creating. For example, you may want to update only one field in a form, but keep the previous347values for all other fields.348349These input fields don’t work because the `oninput` handlers mutate the state:350351```ts352import { createStore } from 'zustand/vanilla'353354type PersonStoreState = {355 person: { firstName: string; lastName: string; email: string }356}357358type PersonStoreActions = {359 setPerson: (nextPerson: PersonStoreState['person']) => void360}361362type PersonStore = PersonStoreState & PersonStoreActions363364const personStore = createStore<PersonStore>()((set) => ({365 person: {366 firstName: 'Barbara',367 lastName: 'Hepworth',368 email: 'bhepworth@sculpture.com',369 },370 setPerson: (person) => set({ person }),371}))372373const $firstNameInput = document.getElementById(374 'first-name',375) as HTMLInputElement376const $lastNameInput = document.getElementById('last-name') as HTMLInputElement377const $emailInput = document.getElementById('email') as HTMLInputElement378const $result = document.getElementById('result') as HTMLDivElement379380function handleFirstNameChange(event: Event) {381 personStore.getState().person.firstName = (event.target as any).value382}383384function handleLastNameChange(event: Event) {385 personStore.getState().person.lastName = (event.target as any).value386}387388function handleEmailChange(event: Event) {389 personStore.getState().person.email = (event.target as any).value390}391392$firstNameInput.addEventListener('input', handleFirstNameChange)393$lastNameInput.addEventListener('input', handleLastNameChange)394$emailInput.addEventListener('input', handleEmailChange)395396const render: Parameters<typeof personStore.subscribe>[0] = (state) => {397 $firstNameInput.value = state.person.firstName398 $lastNameInput.value = state.person.lastName399 $emailInput.value = state.person.email400401 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`402}403404render(personStore.getInitialState(), personStore.getInitialState())405406personStore.subscribe(render)407```408409Here's the `html` code410411```html412<label style="display: block">413 First name:414 <input id="first-name" />415</label>416<label style="display: block">417 Last name:418 <input id="last-name" />419</label>420<label style="display: block">421 Email:422 <input id="email" />423</label>424<p id="result"></p>425```426427For example, this line mutates the state from a past render:428429```ts430personStore.getState().firstName = (e.target as any).value431```432433The reliable way to get the behavior you’re looking for is to create a new object and pass it to434`setPerson`. But here you want to also copy the existing data into it because only one of the435fields has changed:436437```ts438personStore.getState().setPerson({439 firstName: e.target.value, // New first name from the input440})441```442443> [!NOTE]444> We don’t need to copy every property separately due to `set` function performing shallow merge by445> default.446447Now the form works!448449Notice how you didn’t declare a separate state variable for each input field. For large forms,450keeping all data grouped in an object is very convenient—as long as you update it correctly!451452```ts {32-34,38-40,44-46}453import { createStore } from 'zustand/vanilla'454455type PersonStoreState = {456 person: { firstName: string; lastName: string; email: string }457}458459type PersonStoreActions = {460 setPerson: (nextPerson: PersonStoreState['person']) => void461}462463type PersonStore = PersonStoreState & PersonStoreActions464465const personStore = createStore<PersonStore>()((set) => ({466 person: {467 firstName: 'Barbara',468 lastName: 'Hepworth',469 email: 'bhepworth@sculpture.com',470 },471 setPerson: (person) => set({ person }),472}))473474const $firstNameInput = document.getElementById(475 'first-name',476) as HTMLInputElement477const $lastNameInput = document.getElementById('last-name') as HTMLInputElement478const $emailInput = document.getElementById('email') as HTMLInputElement479const $result = document.getElementById('result') as HTMLDivElement480481function handleFirstNameChange(event: Event) {482 personStore.getState().setPerson({483 ...personStore.getState().person,484 firstName: (event.target as any).value,485 })486}487488function handleLastNameChange(event: Event) {489 personStore.getState().setPerson({490 ...personStore.getState().person,491 lastName: (event.target as any).value,492 })493}494495function handleEmailChange(event: Event) {496 personStore.getState().setPerson({497 ...personStore.getState().person,498 email: (event.target as any).value,499 })500}501502$firstNameInput.addEventListener('input', handleFirstNameChange)503$lastNameInput.addEventListener('input', handleLastNameChange)504$emailInput.addEventListener('input', handleEmailChange)505506const render: Parameters<typeof personStore.subscribe>[0] = (state) => {507 $firstNameInput.value = state.person.firstName508 $lastNameInput.value = state.person.lastName509 $emailInput.value = state.person.email510511 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`512}513514render(personStore.getInitialState(), personStore.getInitialState())515516personStore.subscribe(render)517```
deleted:docs/apis/create-with-equality-fn.md-606 removed
1---2title: createWithEqualityFn ⚛️3description: How to create efficient stores4nav: 255---67`createWithEqualityFn` lets you create a React Hook with API utilities attached, just like `create`.8However, it offers a way to define a custom equality check. This allows for more granular control9over when components re-render, improving performance and responsiveness.1011> [!IMPORTANT]12> In order to use `createWithEqualityFn` from `zustand/traditional` you need to install13> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.1415```js16const useSomeStore = createWithEqualityFn(stateCreatorFn, equalityFn)17```1819- [Types](#types)20 - [Signature](#createwithequalityfn-signature)21- [Reference](#reference)22- [Usage](#usage)23 - [Updating state based on previous state](#updating-state-based-on-previous-state)24 - [Updating Primitives in State](#updating-primitives-in-state)25 - [Updating Objects in State](#updating-objects-in-state)26 - [Updating Arrays in State](#updating-arrays-in-state)27 - [Updating state with no store actions](#updating-state-with-no-store-actions)28 - [Subscribing to state updates](#subscribing-to-state-updates)29- [Troubleshooting](#troubleshooting)30 - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)3132## Types3334### Signature3536```ts37createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, equalityFn?: (a: T, b: T) => boolean): UseBoundStore<StoreApi<T>>38```3940## Reference4142### `createWithEqualityFn(stateCreatorFn)`4344#### Parameters4546- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.47 Usually, you will return an object with the methods you want to expose.48- **optional** `equalityFn`: Defaults to `Object.is`. A function that lets you skip re-renders.4950#### Returns5152`createWithEqualityFn` returns a React Hook with API utilities attached, just like `create`. It53lets you return data that is based on current state, using a selector function, and lets you skip54re-renders using an equality function. It should take a selector function, and an equality function55as arguments.5657## Usage5859### Updating state based on previous state6061To update a state based on previous state we should use **updater functions**. Read more62about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).6364This example shows how you can support **updater functions** within **actions**.6566```tsx67import { createWithEqualityFn } from 'zustand/traditional'68import { shallow } from 'zustand/vanilla/shallow'6970type AgeStoreState = { age: number }7172type AgeStoreActions = {73 setAge: (74 nextAge:75 | AgeStoreState['age']76 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),77 ) => void78}7980type AgeStore = AgeStoreState & AgeStoreActions8182const useAgeStore = createWithEqualityFn<AgeStore>()(83 (set) => ({84 age: 42,85 setAge: (nextAge) =>86 set((state) => ({87 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,88 })),89 }),90 shallow,91)9293export default function App() {94 const age = useAgeStore((state) => state.age)95 const setAge = useAgeStore((state) => state.setAge)9697 function increment() {98 setAge((currentAge) => currentAge + 1)99 }100101 return (102 <>103 <h1>Your age: {age}</h1>104 <button105 type="button"106 onClick={() => {107 increment()108 increment()109 increment()110 }}111 >112 +3113 </button>114 <button115 type="button"116 onClick={() => {117 increment()118 }}119 >120 +1121 </button>122 </>123 )124}125```126127### Updating Primitives in State128129State can hold any kind of JavaScript value. When you want to update built-in primitive values like130numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied131correctly, and avoid unexpected behaviors.132133> [!NOTE]134> By default, `set` function performs a shallow merge. If you need to completely replace135> the state with a new one, use the `replace` parameter set to `true`136137```tsx138import { createWithEqualityFn } from 'zustand/traditional'139import { shallow } from 'zustand/vanilla/shallow'140141type XStore = number142143const useXStore = createWithEqualityFn<XStore>()(() => 0, shallow)144145export default function MovingDot() {146 const x = useXStore()147 const setX = (nextX: number) => {148 useXStore.setState(nextX, true)149 }150 const position = { y: 0, x }151152 return (153 <div154 onPointerMove={(e) => {155 setX(e.clientX)156 }}157 style={{158 position: 'relative',159 width: '100vw',160 height: '100vh',161 }}162 >163 <div164 style={{165 position: 'absolute',166 backgroundColor: 'red',167 borderRadius: '50%',168 transform: `translate(${position.x}px, ${position.y}px)`,169 left: -10,170 top: -10,171 width: 20,172 height: 20,173 }}174 />175 </div>176 )177}178```179180### Updating Objects in State181182Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store183them in state. Instead, when you want to update an object, you need to create a new one (or make a184copy of an existing one), and then set the state to use the new object.185186By default, `set` function performs a shallow merge. For most updates where you only need to modify187specific properties, the default shallow merge is preferred as it's more efficient. To completely188replace the state with a new one, use the `replace` parameter set to `true` with caution, as it189discards any existing nested data within the state.190191```tsx192import { createWithEqualityFn } from 'zustand/traditional'193import { shallow } from 'zustand/vanilla/shallow'194195type PositionStoreState = { position: { x: number; y: number } }196197type PositionStoreActions = {198 setPosition: (nextPosition: PositionStoreState['position']) => void199}200201type PositionStore = PositionStoreState & PositionStoreActions202203const usePositionStore = createWithEqualityFn<PositionStore>()(204 (set) => ({205 position: { x: 0, y: 0 },206 setPosition: (position) => set({ position }),207 }),208 shallow,209)210211export default function MovingDot() {212 const position = usePositionStore((state) => state.position)213 const setPosition = usePositionStore((state) => state.setPosition)214215 return (216 <div217 onPointerMove={(e) => {218 setPosition({219 x: e.clientX,220 y: e.clientY,221 })222 }}223 style={{224 position: 'relative',225 width: '100vw',226 height: '100vh',227 }}228 >229 <div230 style={{231 position: 'absolute',232 backgroundColor: 'red',233 borderRadius: '50%',234 transform: `translate(${position.x}px, ${position.y}px)`,235 left: -10,236 top: -10,237 width: 20,238 height: 20,239 }}240 />241 </div>242 )243}244```245246### Updating Arrays in State247248Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in249state. Just like with objects, when you want to update an array stored in state, you need to create250a new one (or make a copy of an existing one), and then set state to use the new array.251252By default, `set` function performs a shallow merge. To update array values we should assign new253values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely254replace the state with a new one, use the `replace` parameter set to `true`.255256> [!IMPORTANT]257> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,258> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid259> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,260> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.261262```tsx263import { createWithEqualityFn } from 'zustand/traditional'264import { shallow } from 'zustand/vanilla/shallow'265266type PositionStore = [number, number]267268const usePositionStore = createWithEqualityFn<PositionStore>()(269 () => [0, 0],270 shallow,271)272273export default function MovingDot() {274 const [x, y] = usePositionStore()275 const position = { x, y }276 const setPosition: typeof usePositionStore.setState = (nextPosition) => {277 usePositionStore.setState(nextPosition, true)278 }279280 return (281 <div282 onPointerMove={(e) => {283 setPosition([e.clientX, e.clientY])284 }}285 style={{286 position: 'relative',287 width: '100vw',288 height: '100vh',289 }}290 >291 <div292 style={{293 position: 'absolute',294 backgroundColor: 'red',295 borderRadius: '50%',296 transform: `translate(${position.x}px, ${position.y}px)`,297 left: -10,298 top: -10,299 width: 20,300 height: 20,301 }}302 />303 </div>304 )305}306```307308### Updating state with no store actions309310Defining actions at module level, external to the store have a few advantages like: it doesn't311require a hook to call an action, and it facilitates code splitting.312313> [!NOTE]314> The recommended way is to colocate actions and states within the store (let your actions be315> located together with your state).316317```tsx318import { createWithEqualityFn } from 'zustand/traditional'319import { shallow } from 'zustand/vanilla/shallow'320321const usePositionStore = createWithEqualityFn<{322 x: number323 y: number324}>()(() => ({ x: 0, y: 0 }), shallow)325326const setPosition: typeof usePositionStore.setState = (nextPosition) => {327 usePositionStore.setState(nextPosition)328}329330export default function MovingDot() {331 const position = usePositionStore()332333 return (334 <div335 style={{336 position: 'relative',337 width: '100vw',338 height: '100vh',339 }}340 >341 <div342 style={{343 position: 'absolute',344 backgroundColor: 'red',345 borderRadius: '50%',346 transform: `translate(${position.x}px, ${position.y}px)`,347 left: -10,348 top: -10,349 width: 20,350 height: 20,351 }}352 onMouseEnter={(event) => {353 const parent = event.currentTarget.parentElement354 const parentWidth = parent.clientWidth355 const parentHeight = parent.clientHeight356357 setPosition({358 x: Math.ceil(Math.random() * parentWidth),359 y: Math.ceil(Math.random() * parentHeight),360 })361 }}362 />363 </div>364 )365}366```367368### Subscribing to state updates369370By subscribing to state updates, you register a callback that fires whenever the store's state371updates. We can use `subscribe` for external state management.372373```tsx374import { useEffect } from 'react'375import { createWithEqualityFn } from 'zustand/traditional'376import { shallow } from 'zustand/vanilla/shallow'377378type PositionStoreState = { position: { x: number; y: number } }379380type PositionStoreActions = {381 setPosition: (nextPosition: PositionStoreState['position']) => void382}383384type PositionStore = PositionStoreState & PositionStoreActions385386const usePositionStore = createWithEqualityFn<PositionStore>()(387 (set) => ({388 position: { x: 0, y: 0 },389 setPosition: (nextPosition) => set({ position: nextPosition }),390 }),391 shallow,392)393394export default function MovingDot() {395 const position = usePositionStore((state) => state.position)396 const setPosition = usePositionStore((state) => state.setPosition)397398 useEffect(() => {399 const unsubscribePositionStore = usePositionStore.subscribe(400 ({ position }) => {401 console.log('new position', { position })402 },403 )404405 return () => {406 unsubscribePositionStore()407 }408 }, [])409410 return (411 <div412 style={{413 position: 'relative',414 width: '100vw',415 height: '100vh',416 }}417 >418 <div419 style={{420 position: 'absolute',421 backgroundColor: 'red',422 borderRadius: '50%',423 transform: `translate(${position.x}px, ${position.y}px)`,424 left: -10,425 top: -10,426 width: 20,427 height: 20,428 }}429 onMouseEnter={(event) => {430 const parent = event.currentTarget.parentElement431 const parentWidth = parent.clientWidth432 const parentHeight = parent.clientHeight433434 setPosition({435 x: Math.ceil(Math.random() * parentWidth),436 y: Math.ceil(Math.random() * parentHeight),437 })438 }}439 />440 </div>441 )442}443```444445## Troubleshooting446447### I’ve updated the state, but the screen doesn’t update448449In the previous example, the `position` object is always created fresh from the current cursor450position. But often, you will want to include existing data as a part of the new object you’re451creating. For example, you may want to update only one field in a form, but keep the previous452values for all other fields.453454These input fields don’t work because the `onChange` handlers mutate the state:455456```tsx457import { createWithEqualityFn } from 'zustand/traditional'458import { shallow } from 'zustand/vanilla/shallow'459460type PersonStoreState = {461 person: { firstName: string; lastName: string; email: string }462}463464type PersonStoreActions = {465 setPerson: (nextPerson: PersonStoreState['person']) => void466}467468type PersonStore = PersonStoreState & PersonStoreActions469470const usePersonStore = createWithEqualityFn<PersonStore>()(471 (set) => ({472 person: {473 firstName: 'Barbara',474 lastName: 'Hepworth',475 email: 'bhepworth@sculpture.com',476 },477 setPerson: (person) => set({ person }),478 }),479 shallow,480)481482export default function Form() {483 const person = usePersonStore((state) => state.person)484 const setPerson = usePersonStore((state) => state.setPerson)485486 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {487 person.firstName = e.target.value488 }489490 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {491 person.lastName = e.target.value492 }493494 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {495 person.email = e.target.value496 }497498 return (499 <>500 <label style={{ display: 'block' }}>501 First name:502 <input value={person.firstName} onChange={handleFirstNameChange} />503 </label>504 <label style={{ display: 'block' }}>505 Last name:506 <input value={person.lastName} onChange={handleLastNameChange} />507 </label>508 <label style={{ display: 'block' }}>509 Email:510 <input value={person.email} onChange={handleEmailChange} />511 </label>512 <p>513 {person.firstName} {person.lastName} ({person.email})514 </p>515 </>516 )517}518```519520For example, this line mutates the state from a past render:521522```tsx523person.firstName = e.target.value524```525526The reliable way to get the behavior you’re looking for is to create a new object and pass it to527`setPerson`. But here you want to also copy the existing data into it because only one of the528fields has changed:529530```ts531setPerson({ ...person, firstName: e.target.value }) // New first name from the input532```533534> [!NOTE]535> We don’t need to copy every property separately due to `set` function performing shallow merge by536> default.537538Now the form works!539540Notice how you didn’t declare a separate state variable for each input field. For large forms,541keeping all data grouped in an object is very convenient—as long as you update it correctly!542543```tsx {32,36,40}544import { type ChangeEvent } from 'react'545import { createWithEqualityFn } from 'zustand/traditional'546import { shallow } from 'zustand/vanilla/shallow'547548type PersonStoreState = {549 person: { firstName: string; lastName: string; email: string }550}551552type PersonStoreActions = {553 setPerson: (nextPerson: PersonStoreState['person']) => void554}555556type PersonStore = PersonStoreState & PersonStoreActions557558const usePersonStore = createWithEqualityFn<PersonStore>()(559 (set) => ({560 person: {561 firstName: 'Barbara',562 lastName: 'Hepworth',563 email: 'bhepworth@sculpture.com',564 },565 setPerson: (nextPerson) => set({ person: nextPerson }),566 }),567 shallow,568)569570export default function Form() {571 const person = usePersonStore((state) => state.person)572 const setPerson = usePersonStore((state) => state.setPerson)573574 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {575 setPerson({ ...person, firstName: e.target.value })576 }577578 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {579 setPerson({ ...person, lastName: e.target.value })580 }581582 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {583 setPerson({ ...person, email: e.target.value })584 }585586 return (587 <>588 <label style={{ display: 'block' }}>589 First name:590 <input value={person.firstName} onChange={handleFirstNameChange} />591 </label>592 <label style={{ display: 'block' }}>593 Last name:594 <input value={person.lastName} onChange={handleLastNameChange} />595 </label>596 <label style={{ display: 'block' }}>597 Email:598 <input value={person.email} onChange={handleEmailChange} />599 </label>600 <p>601 {person.firstName} {person.lastName} ({person.email})602 </p>603 </>604 )605}606```
deleted:docs/apis/create.md-570 removed
1---2title: create ⚛️3description: How to create stores4nav: 265---67`create` lets you create a React Hook with API utilities attached.89```js10const useSomeStore = create(stateCreatorFn)11```1213- [Types](#types)14 - [Signature](#create-signature)15- [Reference](#reference)16- [Usage](#usage)17 - [Updating state based on previous state](#updating-state-based-on-previous-state)18 - [Updating Primitives in State](#updating-primitives-in-state)19 - [Updating Objects in State](#updating-objects-in-state)20 - [Updating Arrays in State](#updating-arrays-in-state)21 - [Updating state with no store actions](#updating-state-with-no-store-actions)22 - [Subscribing to state updates](#subscribing-to-state-updates)23- [Troubleshooting](#troubleshooting)24 - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)2526## Types2728### Signature2930```ts31create<T>()(stateCreatorFn: StateCreator<T, [], []>): UseBoundStore<StoreApi<T>>32```3334## Reference3536### `create(stateCreatorFn)`3738#### Parameters3940- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.41 Usually, you will return an object with the methods you want to expose.4243#### Returns4445`create` returns a React Hook with API utilities, `setState`, `getState`, `getInitialState` and46`subscribe`, attached. It lets you return data that is based on current state, using a selector47function. It should take a selector function as its only argument.4849## Usage5051### Updating state based on previous state5253To update a state based on previous state we should use **updater functions**. Read more54about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).5556This example shows how you can support **updater functions** within **actions**.5758```tsx59import { create } from 'zustand'6061type AgeStoreState = { age: number }6263type AgeStoreActions = {64 setAge: (65 nextAge:66 | AgeStoreState['age']67 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),68 ) => void69}7071type AgeStore = AgeStoreState & AgeStoreActions7273const useAgeStore = create<AgeStore>()((set) => ({74 age: 42,75 setAge: (nextAge) => {76 set((state) => ({77 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,78 }))79 },80}))8182export default function App() {83 const age = useAgeStore((state) => state.age)84 const setAge = useAgeStore((state) => state.setAge)8586 function increment() {87 setAge((currentAge) => currentAge + 1)88 }8990 return (91 <>92 <h1>Your age: {age}</h1>93 <button94 onClick={() => {95 increment()96 increment()97 increment()98 }}99 >100 +3101 </button>102 <button103 onClick={() => {104 increment()105 }}106 >107 +1108 </button>109 </>110 )111}112```113114### Updating Primitives in State115116State can hold any kind of JavaScript value. When you want to update built-in primitive values like117numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied118correctly, and avoid unexpected behaviors.119120> [!NOTE]121> By default, `set` function performs a shallow merge. If you need to completely replace the state122> with a new one, use the `replace` parameter set to `true`123124```tsx125import { create } from 'zustand'126127type XStore = number128129const useXStore = create<XStore>()(() => 0)130131export default function MovingDot() {132 const x = useXStore()133 const setX = (nextX: number) => {134 useXStore.setState(nextX, true)135 }136 const position = { y: 0, x }137138 return (139 <div140 onPointerMove={(e) => {141 setX(e.clientX)142 }}143 style={{144 position: 'relative',145 width: '100vw',146 height: '100vh',147 }}148 >149 <div150 style={{151 position: 'absolute',152 backgroundColor: 'red',153 borderRadius: '50%',154 transform: `translate(${position.x}px, ${position.y}px)`,155 left: -10,156 top: -10,157 width: 20,158 height: 20,159 }}160 />161 </div>162 )163}164```165166### Updating Objects in State167168Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store169them in state. Instead, when you want to update an object, you need to create a new one (or make a170copy of an existing one), and then set the state to use the new object.171172By default, `set` function performs a shallow merge. For most updates where you only need to modify173specific properties, the default shallow merge is preferred as it's more efficient. To completely174replace the state with a new one, use the `replace` parameter set to `true` with caution, as it175discards any existing nested data within the state.176177```tsx178import { create } from 'zustand'179180type PositionStoreState = { position: { x: number; y: number } }181182type PositionStoreActions = {183 setPosition: (nextPosition: PositionStoreState['position']) => void184}185186type PositionStore = PositionStoreState & PositionStoreActions187188const usePositionStore = create<PositionStore>()((set) => ({189 position: { x: 0, y: 0 },190 setPosition: (nextPosition) => set({ position: nextPosition }),191}))192193export default function MovingDot() {194 const position = usePositionStore((state) => state.position)195 const setPosition = usePositionStore((state) => state.setPosition)196197 return (198 <div199 onPointerMove={(e) => {200 setPosition({201 x: e.clientX,202 y: e.clientY,203 })204 }}205 style={{206 position: 'relative',207 width: '100vw',208 height: '100vh',209 }}210 >211 <div212 style={{213 position: 'absolute',214 backgroundColor: 'red',215 borderRadius: '50%',216 transform: `translate(${position.x}px, ${position.y}px)`,217 left: -10,218 top: -10,219 width: 20,220 height: 20,221 }}222 />223 </div>224 )225}226```227228### Updating Arrays in State229230Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in231state. Just like with objects, when you want to update an array stored in state, you need to create232a new one (or make a copy of an existing one), and then set state to use the new array.233234By default, `set` function performs a shallow merge. To update array values we should assign new235values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely236replace the state with a new one, use the `replace` parameter set to `true`.237238> [!IMPORTANT]239> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,240> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid241> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,242> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.243244```tsx245import { create } from 'zustand'246247type PositionStore = [number, number]248249const usePositionStore = create<PositionStore>()(() => [0, 0])250251export default function MovingDot() {252 const [x, y] = usePositionStore()253 const setPosition: typeof usePositionStore.setState = (nextPosition) => {254 usePositionStore.setState(nextPosition, true)255 }256 const position = { x, y }257258 return (259 <div260 onPointerMove={(e) => {261 setPosition([e.clientX, e.clientY])262 }}263 style={{264 position: 'relative',265 width: '100vw',266 height: '100vh',267 }}268 >269 <div270 style={{271 position: 'absolute',272 backgroundColor: 'red',273 borderRadius: '50%',274 transform: `translate(${position.x}px, ${position.y}px)`,275 left: -10,276 top: -10,277 width: 20,278 height: 20,279 }}280 />281 </div>282 )283}284```285286### Updating state with no store actions287288Defining actions at module level, external to the store have a few advantages like: it doesn't289require a hook to call an action, and it facilitates code splitting.290291> [!NOTE]292> The recommended way is to colocate actions and states within the store (let your actions be293> located together with your state).294295```tsx296import { create } from 'zustand'297298const usePositionStore = create<{299 x: number300 y: number301}>()(() => ({ x: 0, y: 0 }))302303const setPosition: typeof usePositionStore.setState = (nextPosition) => {304 usePositionStore.setState(nextPosition)305}306307export default function MovingDot() {308 const position = usePositionStore()309310 return (311 <div312 style={{313 position: 'relative',314 width: '100vw',315 height: '100vh',316 }}317 >318 <div319 style={{320 position: 'absolute',321 backgroundColor: 'red',322 borderRadius: '50%',323 transform: `translate(${position.x}px, ${position.y}px)`,324 left: -10,325 top: -10,326 width: 20,327 height: 20,328 }}329 onMouseEnter={(event) => {330 const parent = event.currentTarget.parentElement331 const parentWidth = parent.clientWidth332 const parentHeight = parent.clientHeight333334 setPosition({335 x: Math.ceil(Math.random() * parentWidth),336 y: Math.ceil(Math.random() * parentHeight),337 })338 }}339 />340 </div>341 )342}343```344345### Subscribing to state updates346347By subscribing to state updates, you register a callback that fires whenever the store's state348updates. We can use `subscribe` for external state management.349350```tsx351import { useEffect } from 'react'352import { create } from 'zustand'353354type PositionStoreState = { position: { x: number; y: number } }355356type PositionStoreActions = {357 setPosition: (nextPosition: PositionStoreState['position']) => void358}359360type PositionStore = PositionStoreState & PositionStoreActions361362const usePositionStore = create<PositionStore>()((set) => ({363 position: { x: 0, y: 0 },364 setPosition: (nextPosition) => set({ position: nextPosition }),365}))366367export default function MovingDot() {368 const position = usePositionStore((state) => state.position)369 const setPosition = usePositionStore((state) => state.setPosition)370371 useEffect(() => {372 const unsubscribePositionStore = usePositionStore.subscribe(373 ({ position }) => {374 console.log('new position', { position })375 },376 )377378 return () => {379 unsubscribePositionStore()380 }381 }, [])382383 return (384 <div385 style={{386 position: 'relative',387 width: '100vw',388 height: '100vh',389 }}390 >391 <div392 style={{393 position: 'absolute',394 backgroundColor: 'red',395 borderRadius: '50%',396 transform: `translate(${position.x}px, ${position.y}px)`,397 left: -10,398 top: -10,399 width: 20,400 height: 20,401 }}402 onMouseEnter={(event) => {403 const parent = event.currentTarget.parentElement404 const parentWidth = parent.clientWidth405 const parentHeight = parent.clientHeight406407 setPosition({408 x: Math.ceil(Math.random() * parentWidth),409 y: Math.ceil(Math.random() * parentHeight),410 })411 }}412 />413 </div>414 )415}416```417418## Troubleshooting419420### I’ve updated the state, but the screen doesn’t update421422In the previous example, the `position` object is always created fresh from the current cursor423position. But often, you will want to include existing data as a part of the new object you’re424creating. For example, you may want to update only one field in a form, but keep the previous425values for all other fields.426427These input fields don’t work because the `onChange` handlers mutate the state:428429```tsx430import { create } from 'zustand'431432type PersonStoreState = {433 firstName: string434 lastName: string435 email: string436}437438type PersonStoreActions = {439 setPerson: (nextPerson: Partial<PersonStoreState>) => void440}441442type PersonStore = PersonStoreState & PersonStoreActions443444const usePersonStore = create<PersonStore>()((set) => ({445 firstName: 'Barbara',446 lastName: 'Hepworth',447 email: 'bhepworth@sculpture.com',448 setPerson: (nextPerson) => set(nextPerson),449}))450451export default function Form() {452 const person = usePersonStore((state) => state)453 const setPerson = usePersonStore((state) => state.setPerson)454455 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {456 person.firstName = e.target.value457 }458459 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {460 person.lastName = e.target.value461 }462463 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {464 person.email = e.target.value465 }466467 return (468 <>469 <label style={{ display: 'block' }}>470 First name:471 <input value={person.firstName} onChange={handleFirstNameChange} />472 </label>473 <label style={{ display: 'block' }}>474 Last name:475 <input value={person.lastName} onChange={handleLastNameChange} />476 </label>477 <label style={{ display: 'block' }}>478 Email:479 <input value={person.email} onChange={handleEmailChange} />480 </label>481 <p>482 {person.firstName} {person.lastName} ({person.email})483 </p>484 </>485 )486}487```488489For example, this line mutates the state from a past render:490491```tsx492person.firstName = e.target.value493```494495The reliable way to get the behavior you’re looking for is to create a new object and pass it to496`setPerson`. But here you want to also copy the existing data into it because only one of the497fields has changed:498499```ts500setPerson({ ...person, firstName: e.target.value }) // New first name from the input501```502503> [!NOTE]504> We don’t need to copy every property separately due to `set` function performing shallow merge by505> default.506507Now the form works!508509Notice how you didn’t declare a separate state variable for each input field. For large forms,510keeping all data grouped in an object is very convenient—as long as you update it correctly!511512```tsx {27,31,35}513import { create } from 'zustand'514515type PersonStoreState = {516 person: { firstName: string; lastName: string; email: string }517}518519type PersonStoreActions = {520 setPerson: (nextPerson: PersonStoreState['person']) => void521}522523type PersonStore = PersonStoreState & PersonStoreActions524525const usePersonStore = create<PersonStore>()((set) => ({526 person: {527 firstName: 'Barbara',528 lastName: 'Hepworth',529 email: 'bhepworth@sculpture.com',530 },531 setPerson: (nextPerson) => set(nextPerson),532}))533534export default function Form() {535 const person = usePersonStore((state) => state.person)536 const setPerson = usePersonStore((state) => state.setPerson)537538 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {539 setPerson({ ...person, firstName: e.target.value })540 }541542 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {543 setPerson({ ...person, lastName: e.target.value })544 }545546 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {547 setPerson({ ...person, email: e.target.value })548 }549550 return (551 <>552 <label style={{ display: 'block' }}>553 First name:554 <input value={person.firstName} onChange={handleFirstNameChange} />555 </label>556 <label style={{ display: 'block' }}>557 Last name:558 <input value={person.lastName} onChange={handleLastNameChange} />559 </label>560 <label style={{ display: 'block' }}>561 Email:562 <input value={person.email} onChange={handleEmailChange} />563 </label>564 <p>565 {person.firstName} {person.lastName} ({person.email})566 </p>567 </>568 )569}570```
deleted:docs/apis/shallow.md-248 removed
1---2title: shallow3description: How compare simple data effectively4nav: 275---67`shallow` lets you run fast checks on simple data structures. It effectively identifies changes in8**top-level** properties when you're working with data structures that don't have nested objects or9arrays within them.1011> [!NOTE]12> Shallow lets you perform quick comparisons, but keep its limitations in mind.1314```js15const equal = shallow(a, b)16```1718- [Types](#types)19 - [Signature](#shallow-signature)20- [Reference](#reference)21- [Usage](#usage)22 - [Comparing Primitives](#comparing-primitives)23 - [Comparing Objects](#comparing-objects)24 - [Comparing Sets](#comparing-sets)25 - [Comparing Maps](#comparing-maps)26- [Troubleshooting](#troubleshooting)27 - [Comparing objects returns `false` even if they are identical.](#comparing-objects-returns-false-even-if-they-are-identical)28 - [Comparing objects with different prototypes](#comparing-objects-with-different-prototypes)2930## Types3132### Signature3334```ts35shallow<T>(a: T, b: T): boolean36```3738## Reference3940### `shallow(a, b)`4142#### Parameters4344- `a`: The first value.45- `b`: The second value.4647#### Returns4849`shallow` returns `true` when `a` and `b` are equal based on a shallow comparison of their50**top-level** properties. Otherwise, it should return `false`.5152## Usage5354### Comparing Primitives5556When comparing primitive values like `string`s, `number`s, `boolean`s, and `BigInt`s, both57`Object.is` and `shallow` function return `true` if the values are the same. This is because58primitive values are compared by their actual value rather than by reference.5960```ts61const stringLeft = 'John Doe'62const stringRight = 'John Doe'6364Object.is(stringLeft, stringRight) // -> true65shallow(stringLeft, stringRight) // -> true6667const numberLeft = 1068const numberRight = 106970Object.is(numberLeft, numberRight) // -> true71shallow(numberLeft, numberRight) // -> true7273const booleanLeft = true74const booleanRight = true7576Object.is(booleanLeft, booleanRight) // -> true77shallow(booleanLeft, booleanRight) // -> true7879const bigIntLeft = 1n80const bigIntRight = 1n8182Object.is(bigIntLeft, bigIntRight) // -> true83shallow(bigIntLeft, bigIntRight) // -> true84```8586### Comparing Objects8788When comparing objects, it's important to understand how `Object.is` and `shallow` function89operate, as they handle comparisons differently.9091The `shallow` function returns `true` because shallow performs a shallow comparison of the objects.92It checks if the top-level properties and their values are the same. In this case, the top-level93properties (`firstName`, `lastName`, and `age`) and their values are identical between `objectLeft`94and `objectRight`, so shallow considers them equal.9596```ts97const objectLeft = {98 firstName: 'John',99 lastName: 'Doe',100 age: 30,101}102const objectRight = {103 firstName: 'John',104 lastName: 'Doe',105 age: 30,106}107108Object.is(objectLeft, objectRight) // -> false109shallow(objectLeft, objectRight) // -> true110```111112### Comparing Sets113114When comparing sets, it's important to understand how `Object.is` and `shallow` function operate,115as they handle comparisons differently.116117The `shallow` function returns `true` because shallow performs a shallow comparison of the sets. It118checks if the top-level properties (in this case, the sets themselves) are the same. Since `setLeft`119and `setRight` are both instances of the Set object and contain the same elements, shallow considers120them equal.121122```ts123const setLeft = new Set([1, 2, 3])124const setRight = new Set([1, 2, 3])125126Object.is(setLeft, setRight) // -> false127shallow(setLeft, setRight) // -> true128```129130### Comparing Maps131132When comparing maps, it's important to understand how `Object.is` and `shallow` function operate, as133they handle comparisons differently.134135The `shallow` returns `true` because shallow performs a shallow comparison of the maps. It checks if136the top-level properties (in this case, the maps themselves) are the same. Since `mapLeft` and137`mapRight` are both instances of the Map object and contain the same key-value pairs, shallow138considers them equal.139140```ts141const mapLeft = new Map([142 [1, 'one'],143 [2, 'two'],144 [3, 'three'],145])146const mapRight = new Map([147 [1, 'one'],148 [2, 'two'],149 [3, 'three'],150])151152Object.is(mapLeft, mapRight) // -> false153shallow(mapLeft, mapRight) // -> true154```155156## Troubleshooting157158### Comparing objects returns `false` even if they are identical.159160The `shallow` function performs a shallow comparison. A shallow comparison checks if the top-level161properties of two objects are equal. It does not check nested objects or deeply nested properties.162In other words, it only compares the references of the properties.163164In the following example, the shallow function returns `false` because it compares only the165top-level properties and their references. The address property in both objects is a nested object,166and even though their contents are identical, their references are different. Consequently, shallow167sees them as different, resulting in `false`.168169```ts170const objectLeft = {171 firstName: 'John',172 lastName: 'Doe',173 age: 30,174 address: {175 street: 'Kulas Light',176 suite: 'Apt. 556',177 city: 'Gwenborough',178 zipcode: '92998-3874',179 geo: {180 lat: '-37.3159',181 lng: '81.1496',182 },183 },184}185const objectRight = {186 firstName: 'John',187 lastName: 'Doe',188 age: 30,189 address: {190 street: 'Kulas Light',191 suite: 'Apt. 556',192 city: 'Gwenborough',193 zipcode: '92998-3874',194 geo: {195 lat: '-37.3159',196 lng: '81.1496',197 },198 },199}200201Object.is(objectLeft, objectRight) // -> false202shallow(objectLeft, objectRight) // -> false203```204205If we remove the `address` property, the shallow comparison would work as expected because all206top-level properties would be primitive values or references to the same values:207208```ts209const objectLeft = {210 firstName: 'John',211 lastName: 'Doe',212 age: 30,213}214const objectRight = {215 firstName: 'John',216 lastName: 'Doe',217 age: 30,218}219220Object.is(objectLeft, objectRight) // -> false221shallow(objectLeft, objectRight) // -> true222```223224In this modified example, `objectLeft` and `objectRight` have the same top-level properties and225primitive values. Since `shallow` function only compares the top-level properties, it will return226`true` because the primitive values (`firstName`, `lastName`, and `age`) are identical in both227objects.228229### Comparing objects with different prototypes230231The `shallow` function checks whether the two objects have the same prototype. If their prototypes232are referentially different, shallow will return `false`. This comparison is done using:233234```ts235Object.getPrototypeOf(a) === Object.getPrototypeOf(b)236```237238> [!IMPORTANT]239> Objects created with the object initializer (`{}`) or with `new Object()` inherit from240> `Object.prototype` by default. However, objects created with `Object.create(proto)` inherit from241> the proto you pass in—which may not be `Object.prototype.`242243```ts244const a = Object.create({}) // -> prototype is `{}`245const b = {} // -> prototype is `Object.prototype`246247shallow(a, b) // -> false248```
deleted:docs/getting-started/comparison.md-483 removed
1---2title: Comparison3description: How Zustand stacks up against similar libraries4nav: 15---67Zustand is one of many state management libraries for React.8On this page we will discuss Zustand9in comparison to some of these libraries,10including Redux, Valtio, Jotai, and Recoil.1112Each library has its own strengths and weaknesses,13and we will compare key differences and similarities between each.1415## Redux1617### State Model (vs Redux)1819Conceptually, Zustand and Redux are quite similar,20both are based on an immutable state model.21However, Redux requires your app to be wrapped22in context providers; Zustand does not.2324**Zustand**2526```ts27import { create } from 'zustand'2829type State = {30 count: number31}3233type Actions = {34 increment: (qty: number) => void35 decrement: (qty: number) => void36}3738const useCountStore = create<State & Actions>((set) => ({39 count: 0,40 increment: (qty: number) => set((state) => ({ count: state.count + qty })),41 decrement: (qty: number) => set((state) => ({ count: state.count - qty })),42}))43```4445```ts46import { create } from 'zustand'4748type State = {49 count: number50}5152type Action = {53 type: 'increment' | 'decrement'54 qty: number55}5657type Actions = {58 dispatch: (action: Action) => void59}6061const countReducer = (state: State, action: Action) => {62 switch (action.type) {63 case 'increment':64 return { count: state.count + action.qty }65 case 'decrement':66 return { count: state.count - action.qty }67 default:68 return state69 }70}7172const useCountStore = create<State & Actions>((set) => ({73 count: 0,74 dispatch: (action: Action) => set((state) => countReducer(state, action)),75}))76```7778**Redux**7980```ts81import { createStore } from 'redux'82import { useSelector, useDispatch } from 'react-redux'8384type State = {85 count: number86}8788type Action = {89 type: 'increment' | 'decrement'90 qty: number91}9293const countReducer = (state: State, action: Action) => {94 switch (action.type) {95 case 'increment':96 return { count: state.count + action.qty }97 case 'decrement':98 return { count: state.count - action.qty }99 default:100 return state101 }102}103104const countStore = createStore(countReducer)105```106107```ts108import { createSlice, configureStore } from '@reduxjs/toolkit'109110const countSlice = createSlice({111 name: 'count',112 initialState: { value: 0 },113 reducers: {114 incremented: (state, qty: number) => {115 // Redux Toolkit does not mutate the state, it uses the Immer library116 // behind scenes, allowing us to have something called "draft state".117 state.value += qty118 },119 decremented: (state, qty: number) => {120 state.value -= qty121 },122 },123})124125const countStore = configureStore({ reducer: countSlice.reducer })126```127128### Render Optimization (vs Redux)129130When it comes to render optimizations within your app,131there are no major differences in approach between Zustand and Redux.132In both libraries it is recommended133that you manually apply render optimizations by using selectors.134135**Zustand**136137```ts138import { create } from 'zustand'139140type State = {141 count: number142}143144type Actions = {145 increment: (qty: number) => void146 decrement: (qty: number) => void147}148149const useCountStore = create<State & Actions>((set) => ({150 count: 0,151 increment: (qty: number) => set((state) => ({ count: state.count + qty })),152 decrement: (qty: number) => set((state) => ({ count: state.count - qty })),153}))154155const Component = () => {156 const count = useCountStore((state) => state.count)157 const increment = useCountStore((state) => state.increment)158 const decrement = useCountStore((state) => state.decrement)159 // ...160}161```162163**Redux**164165```ts166import { createStore } from 'redux'167import { useSelector, useDispatch } from 'react-redux'168169type State = {170 count: number171}172173type Action = {174 type: 'increment' | 'decrement'175 qty: number176}177178const countReducer = (state: State, action: Action) => {179 switch (action.type) {180 case 'increment':181 return { count: state.count + action.qty }182 case 'decrement':183 return { count: state.count - action.qty }184 default:185 return state186 }187}188189const countStore = createStore(countReducer)190191const Component = () => {192 const count = useSelector((state) => state.count)193 const dispatch = useDispatch()194 // ...195}196```197198```ts199import { useSelector } from 'react-redux'200import type { TypedUseSelectorHook } from 'react-redux'201import { createSlice, configureStore } from '@reduxjs/toolkit'202203const countSlice = createSlice({204 name: 'count',205 initialState: { value: 0 },206 reducers: {207 incremented: (state, qty: number) => {208 // Redux Toolkit does not mutate the state, it uses the Immer library209 // behind scenes, allowing us to have something called "draft state".210 state.value += qty211 },212 decremented: (state, qty: number) => {213 state.value -= qty214 },215 },216})217218const countStore = configureStore({ reducer: countSlice.reducer })219220const useAppSelector: TypedUseSelectorHook<typeof countStore.getState> =221 useSelector222223const useAppDispatch: () => typeof countStore.dispatch = useDispatch224225const Component = () => {226 const count = useAppSelector((state) => state.count.value)227 const dispatch = useAppDispatch()228 // ...229}230```231232## Valtio233234### State Model (vs Valtio)235236Zustand and Valtio approach state management237in a fundamentally different way.238Zustand is based on the **immutable** state model,239while Valtio is based on the **mutable** state model.240241**Zustand**242243```ts244import { create } from 'zustand'245246type State = {247 obj: { count: number }248}249250const store = create<State>(() => ({ obj: { count: 0 } }))251252store.setState((prev) => ({ obj: { count: prev.obj.count + 1 } }))253```254255**Valtio**256257```ts258import { proxy } from 'valtio'259260const state = proxy({ obj: { count: 0 } })261262state.obj.count += 1263```264265### Render Optimization (vs Valtio)266267The other difference between Zustand and Valtio268is Valtio makes render optimizations through property access.269However, with Zustand, it is recommended that270you manually apply render optimizations by using selectors.271272**Zustand**273274```ts275import { create } from 'zustand'276277type State = {278 count: number279}280281const useCountStore = create<State>(() => ({282 count: 0,283}))284285const Component = () => {286 const count = useCountStore((state) => state.count)287 // ...288}289```290291**Valtio**292293```ts294import { proxy, useSnapshot } from 'valtio'295296const state = proxy({297 count: 0,298})299300const Component = () => {301 const { count } = useSnapshot(state)302 // ...303}304```305306## Jotai307308### State Model (vs Jotai)309310There is one major difference between Zustand and Jotai.311Zustand is a single store,312while Jotai consists of primitive atoms that can be composed together.313314**Zustand**315316```ts317import { create } from 'zustand'318319type State = {320 count: number321}322323type Actions = {324 updateCount: (325 countCallback: (count: State['count']) => State['count'],326 ) => void327}328329const useCountStore = create<State & Actions>((set) => ({330 count: 0,331 updateCount: (countCallback) =>332 set((state) => ({ count: countCallback(state.count) })),333}))334```335336**Jotai**337338```ts339import { atom } from 'jotai'340341const countAtom = atom<number>(0)342```343344### Render Optimization (vs Jotai)345346Jotai achieves render optimizations through atom dependency.347However, with Zustand it is recommended that348you manually apply render optimizations by using selectors.349350**Zustand**351352```ts353import { create } from 'zustand'354355type State = {356 count: number357}358359type Actions = {360 updateCount: (361 countCallback: (count: State['count']) => State['count'],362 ) => void363}364365const useCountStore = create<State & Actions>((set) => ({366 count: 0,367 updateCount: (countCallback) =>368 set((state) => ({ count: countCallback(state.count) })),369}))370371const Component = () => {372 const count = useCountStore((state) => state.count)373 const updateCount = useCountStore((state) => state.updateCount)374 // ...375}376```377378**Jotai**379380```ts381import { atom, useAtom } from 'jotai'382383const countAtom = atom<number>(0)384385const Component = () => {386 const [count, updateCount] = useAtom(countAtom)387 // ...388}389```390391## Recoil392393### State Model (vs Recoil)394395The difference between Zustand and Recoil396is similar to that between Zustand and Jotai.397Recoil depends on atom string keys398instead of atom object referential identities.399Additionally, Recoil needs to wrap your app in a context provider.400401**Zustand**402403```ts404import { create } from 'zustand'405406type State = {407 count: number408}409410type Actions = {411 setCount: (countCallback: (count: State['count']) => State['count']) => void412}413414const useCountStore = create<State & Actions>((set) => ({415 count: 0,416 setCount: (countCallback) =>417 set((state) => ({ count: countCallback(state.count) })),418}))419```420421**Recoil**422423```ts424import { atom } from 'recoil'425426const count = atom({427 key: 'count',428 default: 0,429})430```431432### Render Optimization (vs Recoil)433434Similar to previous optimization comparisons,435Recoil makes render optimizations through atom dependency.436Whereas with Zustand, it is recommended that437you manually apply render optimizations by using selectors.438439**Zustand**440441```ts442import { create } from 'zustand'443444type State = {445 count: number446}447448type Actions = {449 setCount: (countCallback: (count: State['count']) => State['count']) => void450}451452const useCountStore = create<State & Actions>((set) => ({453 count: 0,454 setCount: (countCallback) =>455 set((state) => ({ count: countCallback(state.count) })),456}))457458const Component = () => {459 const count = useCountStore((state) => state.count)460 const setCount = useCountStore((state) => state.setCount)461 // ...462}463```464465**Recoil**466467```ts468import { atom, useRecoilState } from 'recoil'469470const countAtom = atom({471 key: 'count',472 default: 0,473})474475const Component = () => {476 const [count, setCount] = useRecoilState(countAtom)477 // ...478}479```480481## Npm Downloads Trend482483- [Npm Downloads Trend of State Management Libraries for React](https://npm-stat.com/charts.html?package=zustand&package=jotai&package=valtio&package=%40reduxjs%2Ftoolkit&package=recoil)
deleted:docs/getting-started/introduction.md-72 removed
deleted:docs/guides/advanced-typescript.md-542 removed
1---2title: Advanced TypeScript Guide3nav: 74---56## Basic usage78The difference when using TypeScript is that instead of writing `create(...)`, you have to write `create<T>()(...)` (notice the extra parentheses `()` too along with the type parameter) where `T` is the type of the state to annotate it. For example:910```ts11import { create } from 'zustand'1213interface BearState {14 bears: number15 increase: (by: number) => void16}1718const useBearStore = create<BearState>()((set) => ({19 bears: 0,20 increase: (by) => set((state) => ({ bears: state.bears + by })),21}))22```2324<details>25 <summary>Why can't we simply infer the type from the initial state?</summary>2627 <br/>2829**TLDR**: Because state generic `T` is invariant.3031Consider this minimal version `create`:3233```ts34declare const create: <T>(f: (get: () => T) => T) => T3536const x = create((get) => ({37 foo: 0,38 bar: () => get(),39}))40// `x` is inferred as `unknown` instead of41// interface X {42// foo: number,43// bar: () => X44// }45```4647Here, if you look at the type of `f` in `create`, i.e. `(get: () => T) => T`, it "gives" `T` via return (making it covariant), but it also "takes" `T` via `get` (making it contravariant). "So where does `T` come from?" TypeScript wonders. It's like that chicken or egg problem. At the end TypeScript, gives up and infers `T` as `unknown`.4849So, as long as the generic to be inferred is invariant (i.e. both covariant and contravariant), TypeScript will be unable to infer it. Another simple example would be this:5051```ts52const createFoo = {} as <T>(f: (t: T) => T) => T53const x = createFoo((_) => 'hello')54```5556Here again, `x` is `unknown` instead of `string`.5758 <details>59 <summary>More about the inference (just for the people curious and interested in TypeScript)</summary>6061In some sense this inference failure is not a problem because a value of type `<T>(f: (t: T) => T) => T` cannot be written. That is to say you can't write the real runtime implementation of `createFoo`. Let's try it:6263```js64const createFoo = (f) => f(/* ? */)65```6667`createFoo` needs to return the return value of `f`. And to do that we first have to call `f`. And to call it we have to pass a value of type `T`. And to pass a value of type `T` we first have to produce it. But how can we produce a value of type `T` when we don't even know what `T` is? The only way to produce a value of type `T` is to call `f`, but then to call `f` itself we need a value of type `T`. So you see it's impossible to actually write `createFoo`.6869So what we're saying is, the inference failure in case of `createFoo` is not really a problem because it's impossible to implement `createFoo`. But what about the inference failure in case of `create`? That also is not really a problem because it's impossible to implement `create` too. Wait a minute, if it's impossible to implement `create` then how does Zustand implement it? The answer is, it doesn't.7071Zustand lies that it implemented `create`'s type, it implemented only the most part of it. Here's a simple proof by showing unsoundness. Consider the following code:7273```ts74import { create } from 'zustand'7576const useBoundStore = create<{ foo: number }>()((_, get) => ({77 foo: get().foo,78}))79```8081This code compiles. But if we run it, we'll get an exception: "Uncaught TypeError: Cannot read properties of undefined (reading 'foo')". This is because `get` would return `undefined` before the initial state is created (hence you shouldn't call `get` when creating the initial state). The types promise that `get` will never return `undefined` but it does initially, which means Zustand failed to implement it.8283And of course Zustand failed because it's impossible to implement `create` the way types promise (in the same way it's impossible to implement `createFoo`). In other words we don't have a type to express the actual `create` we have implemented. We can't type `get` as `() => T | undefined` because it would cause inconvenience and it still won't be correct as `get` is indeed `() => T` eventually, just if called synchronously it would be `() => undefined`. What we need is some kind of TypeScript feature that allows us to type `get` as `(() => T) & WhenSync<() => undefined>`, which of course is extremely far-fetched.8485So we have two problems: lack of inference and unsoundness. Lack of inference can be solved if TypeScript can improve its inference for invariants. And unsoundness can be solved if TypeScript introduces something like `WhenSync`. To work around lack of inference we manually annotate the state type. And we can't work around unsoundness, but it's not a big deal because it's not much, calling `get` synchronously anyway doesn't make sense.8687</details>8889</details>9091<details>92 <summary>Why the currying `()(...)`?</summary>9394 <br/>9596**TLDR**: It is a workaround for [microsoft/TypeScript#10571](https://github.com/microsoft/TypeScript/issues/10571).9798Imagine you have a scenario like this:99100```ts101declare const withError: <T, E>(102 p: Promise<T>,103) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>104declare const doSomething: () => Promise<string>105106const main = async () => {107 let [error, value] = await withError(doSomething())108}109```110111Here, `T` is inferred to be a `string` and `E` is inferred to be `unknown`. You might want to annotate `E` as `Foo`, because you are certain of the shape of error `doSomething()` would throw. However, you can't do that. You can either pass all generics or none. Along with annotating `E` as `Foo`, you will also have to annotate `T` as `string` even though it gets inferred anyway. The solution is to make a curried version of `withError` that does nothing at runtime. Its purpose is to just allow you annotate `E`.112113```ts114declare const withError: {115 <E>(): <T>(116 p: Promise<T>,117 ) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>118 <T, E>(119 p: Promise<T>,120 ): Promise<[error: undefined, value: T] | [error: E, value: undefined]>121}122declare const doSomething: () => Promise<string>123interface Foo {124 bar: string125}126127const main = async () => {128 let [error, value] = await withError<Foo>()(doSomething())129}130```131132This way, `T` gets inferred and you get to annotate `E`. Zustand has the same use case when we want to annotate the state (the first type parameter) but allow other parameters to get inferred.133134</details>135136Alternatively, you can also use `combine`, which infers the state so that you do not need to type it.137138```ts139import { create } from 'zustand'140import { combine } from 'zustand/middleware'141142const useBearStore = create(143 combine({ bears: 0 }, (set) => ({144 increase: (by: number) => set((state) => ({ bears: state.bears + by })),145 })),146)147```148149<details>150 <summary>Be a little careful</summary>151152 <br/>153154We achieve the inference by lying a little in the types of `set`, `get`, and `store` that you receive as parameters. The lie is that they're typed as if the state is the first parameter, when in fact the state is the shallow-merge (`{ ...a, ...b }`) of both first parameter and the second parameter's return. For example, `get` from the second parameter has type `() => { bears: number }` and that is a lie as it should be `() => { bears: number, increase: (by: number) => void }`. And `useBearStore` still has the correct type; for example, `useBearStore.getState` is typed as `() => { bears: number, increase: (by: number) => void }`.155156It isn't really a lie because `{ bears: number }` is still a subtype of `{ bears: number, increase: (by: number) => void }`. Therefore, there will be no problem in most cases. You should just be careful while using replace. For example, `set({ bears: 0 }, true)` would compile but will be unsound as it will delete the `increase` function. Another instance where you should be careful is if you use `Object.keys`. `Object.keys(get())` will return `["bears", "increase"]` and not `["bears"]`. The return type of `get` can make you fall for these mistakes.157158`combine` trades off a little type-safety for the convenience of not having to write a type for state. Hence, you should use `combine` accordingly. It is fine in most cases and you can use it conveniently.159160</details>161162Note that we don't use the curried version when using `combine` because `combine` "creates" the state. When using a middleware that creates the state, it isn't necessary to use the curried version because the state now can be inferred. Another middleware that creates state is `redux`. So when using `combine`, `redux`, or any other custom middleware that creates the state, we don't recommend using the curried version.163164If you want to infer state type also outside of state declaration, you can use the `ExtractState` type helper:165166```ts167import { create, ExtractState } from 'zustand'168import { combine } from 'zustand/middleware'169170type BearState = ExtractState<typeof useBearStore>171172const useBearStore = create(173 combine({ bears: 0 }, (set) => ({174 increase: (by: number) => set((state) => ({ bears: state.bears + by })),175 })),176)177```178179## Using middlewares180181You do not have to do anything special to use middlewares in TypeScript.182183```ts184import { create } from 'zustand'185import { devtools, persist } from 'zustand/middleware'186187interface BearState {188 bears: number189 increase: (by: number) => void190}191192const useBearStore = create<BearState>()(193 devtools(194 persist(195 (set) => ({196 bears: 0,197 increase: (by) => set((state) => ({ bears: state.bears + by })),198 }),199 { name: 'bearStore' },200 ),201 ),202)203```204205Just make sure you are using them immediately inside `create` so as to make the contextual inference work. Doing something even remotely fancy like the following `myMiddlewares` would require more advanced types.206207```ts208import { create } from 'zustand'209import { devtools, persist } from 'zustand/middleware'210211const myMiddlewares = (f) => devtools(persist(f, { name: 'bearStore' }))212213interface BearState {214 bears: number215 increase: (by: number) => void216}217218const useBearStore = create<BearState>()(219 myMiddlewares((set) => ({220 bears: 0,221 increase: (by) => set((state) => ({ bears: state.bears + by })),222 })),223)224```225226Also, we recommend using `devtools` middleware as last as possible. For example, when you use it with `immer` as a middleware, it should be `devtools(immer(...))` and not `immer(devtools(...))`. This is because`devtools` mutates the `setState` and adds a type parameter on it, which could get lost if other middlewares (like `immer`) also mutate `setState` before `devtools`. Hence using `devtools` at the end makes sure that no middlewares mutate `setState` before it.227228## Authoring middlewares and advanced usage229230Imagine you had to write this hypothetical middleware.231232```ts233import { create } from 'zustand'234235const foo = (f, bar) => (set, get, store) => {236 store.foo = bar237 return f(set, get, store)238}239240const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))241console.log(useBearStore.foo.toUpperCase())242```243244Zustand middlewares can mutate the store. But how could we possibly encode the mutation on the type-level? That is to say how could we type `foo` so that this code compiles?245246For a usual statically typed language, this is impossible. But thanks to TypeScript, Zustand has something called a "higher-kinded mutator" that makes this possible. If you are dealing with complex type problems, like typing a middleware or using the `StateCreator` type, you will have to understand this implementation detail. For this, you can [check out #710](https://github.com/pmndrs/zustand/issues/710).247248If you are eager to know what the answer is to this particular problem then you can [see it here](#middleware-that-changes-the-store-type).249250### Handling Dynamic `replace` Flag251252If the value of the `replace` flag is not known at compile time and is determined dynamically, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:253254```ts255const replaceFlag = Math.random() > 0.5256const args = [{ bears: 5 }, replaceFlag] as Parameters<257 typeof useBearStore.setState258>259store.setState(...args)260```261262#### Example with `as Parameters` Workaround263264```ts265import { create } from 'zustand'266267interface BearState {268 bears: number269 increase: (by: number) => void270}271272const useBearStore = create<BearState>()((set) => ({273 bears: 0,274 increase: (by) => set((state) => ({ bears: state.bears + by })),275}))276277const replaceFlag = Math.random() > 0.5278const args = [{ bears: 5 }, replaceFlag] as Parameters<279 typeof useBearStore.setState280>281useBearStore.setState(...args) // Using the workaround282```283284By following this approach, you can ensure that your code handles dynamic `replace` flags without encountering type issues.285286## Common recipes287288### Middleware that doesn't change the store type289290```ts291import { create, StateCreator, StoreMutatorIdentifier } from 'zustand'292293type Logger = <294 T,295 Mps extends [StoreMutatorIdentifier, unknown][] = [],296 Mcs extends [StoreMutatorIdentifier, unknown][] = [],297>(298 f: StateCreator<T, Mps, Mcs>,299 name?: string,300) => StateCreator<T, Mps, Mcs>301302type LoggerImpl = <T>(303 f: StateCreator<T, [], []>,304 name?: string,305) => StateCreator<T, [], []>306307const loggerImpl: LoggerImpl = (f, name) => (set, get, store) => {308 const loggedSet: typeof set = (...a) => {309 set(...(a as Parameters<typeof set>))310 console.log(...(name ? [`${name}:`] : []), get())311 }312 const setState = store.setState313 store.setState = (...a) => {314 setState(...(a as Parameters<typeof setState>))315 console.log(...(name ? [`${name}:`] : []), store.getState())316 }317318 return f(loggedSet, get, store)319}320321export const logger = loggerImpl as unknown as Logger322323// ---324325const useBearStore = create<BearState>()(326 logger(327 (set) => ({328 bears: 0,329 increase: (by) => set((state) => ({ bears: state.bears + by })),330 }),331 'bear-store',332 ),333)334```335336### Middleware that changes the store type337338```ts339import {340 create,341 StateCreator,342 StoreMutatorIdentifier,343 Mutate,344 StoreApi,345} from 'zustand'346347type Foo = <348 T,349 A,350 Mps extends [StoreMutatorIdentifier, unknown][] = [],351 Mcs extends [StoreMutatorIdentifier, unknown][] = [],352>(353 f: StateCreator<T, [...Mps, ['foo', A]], Mcs>,354 bar: A,355) => StateCreator<T, Mps, [['foo', A], ...Mcs]>356357declare module 'zustand' {358 interface StoreMutators<S, A> {359 foo: Write<Cast<S, object>, { foo: A }>360 }361}362363type FooImpl = <T, A>(364 f: StateCreator<T, [], []>,365 bar: A,366) => StateCreator<T, [], []>367368const fooImpl: FooImpl = (f, bar) => (set, get, _store) => {369 type T = ReturnType<typeof f>370 type A = typeof bar371372 const store = _store as Mutate<StoreApi<T>, [['foo', A]]>373 store.foo = bar374 return f(set, get, _store)375}376377export const foo = fooImpl as unknown as Foo378379type Write<T extends object, U extends object> = Omit<T, keyof U> & U380381type Cast<T, U> = T extends U ? T : U382383// ---384385const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))386console.log(useBearStore.foo.toUpperCase())387```388389### `create` without curried workaround390391The recommended way to use `create` is using the curried workaround like so: `create<T>()(...)`. This is because it enables you to infer the store type. But if for some reason you do not want to use the workaround, you can pass the type parameters like the following. Note that in some cases, this acts as an assertion instead of annotation, so we don't recommend it.392393```ts394import { create } from "zustand"395396interface BearState {397 bears: number398 increase: (by: number) => void399}400401const useBearStore = create<402 BearState,403 [404 ['zustand/persist', BearState],405 ['zustand/devtools', never]406 ]407>(devtools(persist((set) => ({408 bears: 0,409 increase: (by) => set((state) => ({ bears: state.bears + by })),410}), { name: 'bearStore' }))411```412413### Slices pattern414415```ts416import { create, StateCreator } from 'zustand'417418interface BearSlice {419 bears: number420 addBear: () => void421 eatFish: () => void422}423424interface FishSlice {425 fishes: number426 addFish: () => void427}428429interface SharedSlice {430 addBoth: () => void431 getBoth: () => number432}433434const createBearSlice: StateCreator<435 BearSlice & FishSlice,436 [],437 [],438 BearSlice439> = (set) => ({440 bears: 0,441 addBear: () => set((state) => ({ bears: state.bears + 1 })),442 eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),443})444445const createFishSlice: StateCreator<446 BearSlice & FishSlice,447 [],448 [],449 FishSlice450> = (set) => ({451 fishes: 0,452 addFish: () => set((state) => ({ fishes: state.fishes + 1 })),453})454455const createSharedSlice: StateCreator<456 BearSlice & FishSlice,457 [],458 [],459 SharedSlice460> = (set, get) => ({461 addBoth: () => {462 // you can reuse previous methods463 get().addBear()464 get().addFish()465 // or do them from scratch466 // set((state) => ({ bears: state.bears + 1, fishes: state.fishes + 1 })467 },468 getBoth: () => get().bears + get().fishes,469})470471const useBoundStore = create<BearSlice & FishSlice & SharedSlice>()((...a) => ({472 ...createBearSlice(...a),473 ...createFishSlice(...a),474 ...createSharedSlice(...a),475}))476```477478A detailed explanation on the slices pattern can be found [here](./slices-pattern.md).479480If you have some middlewares then replace `StateCreator<MyState, [], [], MySlice>` with `StateCreator<MyState, Mutators, [], MySlice>`. For example, if you are using `devtools` then it will be `StateCreator<MyState, [["zustand/devtools", never]], [], MySlice>`. See the ["Middlewares and their mutators reference"](#middlewares-and-their-mutators-reference) section for a list of all mutators.481482### Bounded `useStore` hook for vanilla stores483484```ts485import { useStore } from 'zustand'486import { createStore } from 'zustand/vanilla'487488interface BearState {489 bears: number490 increase: (by: number) => void491}492493const bearStore = createStore<BearState>()((set) => ({494 bears: 0,495 increase: (by) => set((state) => ({ bears: state.bears + by })),496}))497498function useBearStore(): BearState499function useBearStore<T>(selector: (state: BearState) => T): T500function useBearStore<T>(selector?: (state: BearState) => T) {501 return useStore(bearStore, selector!)502}503```504505You can also make an abstract `createBoundedUseStore` function if you need to create bounded `useStore` hooks often and want to DRY things up...506507```ts508import { useStore, StoreApi } from 'zustand'509import { createStore } from 'zustand/vanilla'510511interface BearState {512 bears: number513 increase: (by: number) => void514}515516const bearStore = createStore<BearState>()((set) => ({517 bears: 0,518 increase: (by) => set((state) => ({ bears: state.bears + by })),519}))520521const createBoundedUseStore = ((store) => (selector) =>522 useStore(store, selector)) as <S extends StoreApi<unknown>>(523 store: S,524) => {525 (): ExtractState<S>526 <T>(selector: (state: ExtractState<S>) => T): T527}528529type ExtractState<S> = S extends { getState: () => infer X } ? X : never530531const useBearStore = createBoundedUseStore(bearStore)532```533534## Middlewares and their mutators reference535536- `devtools` — `["zustand/devtools", never]`537- `persist` — `["zustand/persist", YourPersistedState]`<br/>538 `YourPersistedState` is the type of state you are going to persist, ie the return type of `options.partialize`, if you're not passing `partialize` options the `YourPersistedState` becomes `Partial<YourState>`. Also [sometimes](https://github.com/pmndrs/zustand/issues/980#issuecomment-1162289836) passing actual `PersistedState` won't work. In those cases, try passing `unknown`.539- `immer` — `["zustand/immer", never]`540- `subscribeWithSelector` — `["zustand/subscribeWithSelector", never]`541- `redux` — `["zustand/redux", YourAction]`542- `combine` — no mutator as `combine` does not mutate the store
deleted:docs/guides/auto-generating-selectors.md-134 removed
1---2title: Auto Generating Selectors3nav: 54---56We recommend using selectors when using either the properties or actions from the store. You can access values from the store like so:78```typescript9const bears = useBearStore((state) => state.bears)10```1112However, writing these could be tedious. If that is the case for you, you can auto-generate your selectors.1314## Create the following function: `createSelectors`1516```typescript17import { StoreApi, UseBoundStore } from 'zustand'1819type WithSelectors<S> = S extends { getState: () => infer T }20 ? S & { use: { [K in keyof T]: () => T[K] } }21 : never2223const createSelectors = <S extends UseBoundStore<StoreApi<object>>>(24 _store: S,25) => {26 const store = _store as WithSelectors<typeof _store>27 store.use = {}28 for (const k of Object.keys(store.getState())) {29 ;(store.use as any)[k] = () => store((s) => s[k as keyof typeof s])30 }3132 return store33}34```3536If you have a store like this:3738```typescript39interface BearState {40 bears: number41 increase: (by: number) => void42 increment: () => void43}4445const useBearStoreBase = create<BearState>()((set) => ({46 bears: 0,47 increase: (by) => set((state) => ({ bears: state.bears + by })),48 increment: () => set((state) => ({ bears: state.bears + 1 })),49}))50```5152Apply that function to your store:5354```typescript55const useBearStore = createSelectors(useBearStoreBase)56```5758Now the selectors are auto generated and you can access them directly:5960```typescript61// get the property62const bears = useBearStore.use.bears()6364// get the action65const increment = useBearStore.use.increment()66```6768## Vanilla Store6970If you are using a vanilla store, use the following `createSelectors` function:7172```typescript73import { StoreApi, useStore } from 'zustand'7475type WithSelectors<S> = S extends { getState: () => infer T }76 ? S & { use: { [K in keyof T]: () => T[K] } }77 : never7879const createSelectors = <S extends StoreApi<object>>(_store: S) => {80 const store = _store as WithSelectors<typeof _store>81 store.use = {}82 for (const k of Object.keys(store.getState())) {83 ;(store.use as any)[k] = () =>84 useStore(_store, (s) => s[k as keyof typeof s])85 }8687 return store88}89```9091The usage is the same as a React store. If you have a store like this:9293```typescript94import { createStore } from 'zustand'9596interface BearState {97 bears: number98 increase: (by: number) => void99 increment: () => void100}101102const store = createStore<BearState>()((set) => ({103 bears: 0,104 increase: (by) => set((state) => ({ bears: state.bears + by })),105 increment: () => set((state) => ({ bears: state.bears + 1 })),106}))107```108109Apply that function to your store:110111```typescript112const useBearStore = createSelectors(store)113```114115Now the selectors are auto generated and you can access them directly:116117```typescript118// get the property119const bears = useBearStore.use.bears()120121// get the action122const increment = useBearStore.use.increment()123```124125## Live Demo126127For a working example of this, see the [Code Sandbox](https://codesandbox.io/s/zustand-auto-generate-selectors-forked-rl8v5e?file=/src/selectors.ts).128129## Third-party Libraries130131- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook)132- [react-hooks-global-state](https://github.com/dai-shi/react-hooks-global-state)133- [zustood](https://github.com/udecode/zustood)134- [@davstack/store](https://github.com/DawidWraga/davstack)
deleted:docs/guides/beginner-typescript.md-378 removed
1---2title: Beginner TypeScript Guide3nav: 74---56Zustand is a lightweight state manager, particularly used with React. Zustand avoids reducers, context, and boilerplate.7Paired with TypeScript, you get a strongly typed store-state, actions, and selectors-with autocomplete and compile-time safety.89In this basic guide we’ll cover:1011- Creating a typed store (state + actions)12- Using the store in React components with type safety13- Resetting the store safely with types14- Extracting and reusing Store type (for props, tests, and utilities)15- Composing multiple selectors and building derived state (with type inference and without extra re-renders)16- Middlewares with TypeScript support (`combine`, `devtools`, `persist`)17- Async actions with typed API responses18- Working with `createWithEqualityFn` (enhanced `create` store function)19- Structuring and coordinating multiple stores2021### Creating a Store with State & Actions2223Here we describe state and actions using an Typescript interface. The `<BearState>` generic forces the store to match this shape.24This means if you forget a field or use the wrong type, TypeScript will complain. Unlike plain JS, this guarantees type-safe state management.25The `create` function uses the curried form, which results in a store of type `UseBoundStore<StoreApi<BearState>>`.2627```ts28// store.ts29import { create } from 'zustand'3031// Define types for state & actions32interface BearState {33 bears: number34 food: string35 feed: (food: string) => void36}3738// Create store using the curried form of `create`39export const useBearStore = create<BearState>()((set) => ({40 bears: 2,41 food: 'honey',42 feed: (food) => set(() => ({ food })),43}))44```4546### Using the Store in Components4748Inside components, you can read state and call actions. Selectors `(s) => s.bears` subscribe to only what you need.49This reduces re-renders and improves performance. JS can do this too, but with TS your IDE autocompletes state fields.5051```tsx52import { useBearStore } from './store'5354function BearCounter() {55 // Select only 'bears' to avoid unnecessary re-renders56 const bears = useBearStore((s) => s.bears)57 return <h1>{bears} bears around</h1>58}59```6061### Resetting the Store6263Resetting is useful after logout or “clear session”. We use `typeof initialState` to avoid repeating property types.64TypeScript updates automatically if `initialState` changes. This is safer and cleaner compared to JS.6566```tsx67import { create } from 'zustand'6869const initialState = { bears: 0, food: 'honey' }7071// Reuse state type dynamically72type BearState = typeof initialState & {73 increase: (by: number) => void74 reset: () => void75}7677const useBearStore = create<BearState>()((set) => ({78 ...initialState,79 increase: (by) => set((s) => ({ bears: s.bears + by })),80 reset: () => set(initialState),81}))8283function ResetZoo() {84 const { bears, increase, reset } = useBearStore()8586 return (87 <div>88 <div>{bears}</div>89 <button onClick={() => increase(5)}>Increase by 5</button>90 <button onClick={reset}>Reset</button>91 </div>92 )93}94```9596### Extracting Types9798Zustand provides a built-in helper called `ExtractState`. This is useful for tests, utility functions, or component props.99It returns the full type of your store’s state and actions without having to manually redefine them. Extracting the Store type:100101```ts102// store.ts103import { create, type ExtractState } from 'zustand'104105export const useBearStore = create((set) => ({106 bears: 3,107 food: 'honey',108 increase: (by: number) => set((s) => ({ bears: s.bears + by })),109}))110111// Extract the type of the whole store state112export type BearState = ExtractState<typeof useBearStore>113```114115Using extracted type in tests:116117```ts118// test.cy.ts119import { BearState } from './store.ts'120121test('should reset store', () => {122 const snapshot: BearState = useBearStore.getState()123 expect(snapshot.bears).toBeGreaterThanOrEqual(0)124})125```126127and in utility function:128129```ts130// util.ts131import { BearState } from './store.ts'132133function logBearState(state: BearState) {134 console.log(`We have ${state.bears} bears eating ${state.food}`)135}136137logBearState(useBearStore.getState())138```139140### Selectors141142#### Multiple Selectors143144Sometimes you need more than one property. Returning an object from the selector lets you access multiple fields at once.145However, directly destructuring properties from that object can cause unnecessary re-renders.146To avoid this, it’s recommended to wrap the selector with `useShallow`, which prevents re-renders when the selected values remain shallowly equal.147This is more efficient than subscribing to the whole store. TypeScript ensures you can’t accidentally misspell `bears` or `food`.148See the [API documentation](https://zustand.docs.pmnd.rs/hooks/use-shallow) for more details on `useShallow`.149150```tsx151import { create } from 'zustand'152import { useShallow } from 'zustand/react/shallow'153154// Bear store with explicit types155interface BearState {156 bears: number157 food: number158}159160const useBearStore = create<BearState>()(() => ({161 bears: 2,162 food: 10,163}))164165// In components, you can use both stores safely166function MultipleSelectors() {167 const { bears, food } = useBearStore(168 useShallow((state) => ({ bears: state.bears, food: state.food })),169 )170171 return (172 <div>173 We have {food} units of food for {bears} bears174 </div>175 )176}177```178179#### Derived State with Selectors180181Not all values need to be stored directly - some can be computed from existing state. You can derive values using selectors.182This avoids duplication and keeps the store minimal. TypeScript ensures `bears` is a number, so math is safe.183184```tsx185import { create } from 'zustand'186187interface BearState {188 bears: number189 foodPerBear: number190}191192const useBearStore = create<BearState>()(() => ({193 bears: 3,194 foodPerBear: 2,195}))196197function TotalFood() {198 // Derived value: required amount food for all bears199 const totalFood = useBearStore((s) => s.bears * s.foodPerBear) // don't need to have extra property `{ totalFood: 6 }` in your Store200201 return <div>We need ${totalFood} jars of honey</div>202}203```204205### Middlewares206207#### `combine` middleware208209This middleware separates initial state and actions, making the code cleaner.210TS automatically infers types from the state and actions, no interface needed.211This is different from JS, where type safety is missing. It’s a very popular style in TypeScript projects.212See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/combine) for more details.213214```ts215import { create } from 'zustand'216import { combine } from 'zustand/middleware'217218interface BearState {219 bears: number220 increase: () => void221}222223// State + actions are separated224export const useBearStore = create<BearState>()(225 combine({ bears: 0 }, (set) => ({226 increase: () => set((s) => ({ bears: s.bears + 1 })),227 })),228)229```230231#### `devtools` middleware232233This middleware connects Zustand to Redux DevTools. You can inspect changes, time-travel, and debug state.234It’s extremely useful in development. TS ensures your actions and state remain type-checked even here.235See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/devtools) for more details.236237```ts238import { create } from 'zustand'239import { devtools } from 'zustand/middleware'240241interface BearState {242 bears: number243 increase: () => void244}245246export const useBearStore = create<BearState>()(247 devtools((set) => ({248 bears: 0,249 increase: () => set((s) => ({ bears: s.bears + 1 })),250 })),251)252```253254#### `persist` middleware255256This middleware keeps your store in `localStorage` (or another storage). This means your bears survive a page refresh.257Great for apps where persistence matters. In TS, the state type stays consistent, so no runtime surprises.258See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/persist) for more details.259260```ts261import { create } from 'zustand'262import { persist } from 'zustand/middleware'263264interface BearState {265 bears: number266 increase: () => void267}268269export const useBearStore = create<BearState>()(270 persist(271 (set) => ({272 bears: 0,273 increase: () => set((s) => ({ bears: s.bears + 1 })),274 }),275 { name: 'bear-storage' }, // localStorage key276 ),277)278```279280### Async Actions281282Actions can be async to fetch remote data. Here we fetch bears count and update state.283TS enforces correct API response type (`BearData`). In JS you might misspell `count` - TS prevents that.284285```ts286import { create } from 'zustand'287288interface BearData {289 count: number290}291292interface BearState {293 bears: number294 fetchBears: () => Promise<void>295}296297export const useBearStore = create<BearState>()((set) => ({298 bears: 0,299 fetchBears: async () => {300 const res = await fetch('/api/bears')301 const data: BearData = await res.json()302303 set({ bears: data.count })304 },305}))306```307308### `createWithEqualityFn`309310Variant of `create` with equality built-in. Useful if you always want custom equality checks.311Not common, but shows Zustand’s flexibility. TS still keeps full type inference.312See the [API documentation](https://zustand.docs.pmnd.rs/apis/create-with-equality-fn) for more details.313314```ts315import { createWithEqualityFn } from 'zustand/traditional'316import { shallow } from 'zustand/shallow'317318const useBearStore = createWithEqualityFn(() => ({319 bears: 0,320}))321322const bears = useBearStore((s) => s.bears, Object.is)323// or324const bears = useBearStore((s) => ({ bears: s.bears }), shallow)325```326327### Multiple Stores328329You can create more than one store for different domains. For example, `BearStore` manages bears and `FishStore` manages fish.330This keeps state isolated and easier to maintain in larger apps. With TypeScript, each store has its own strict type - you can’t accidentally mix bears and fish.331332```tsx333import { create } from 'zustand'334335// Bear store with explicit types336interface BearState {337 bears: number338 addBear: () => void339}340341const useBearStore = create<BearState>()((set) => ({342 bears: 2,343 addBear: () => set((s) => ({ bears: s.bears + 1 })),344}))345346// Fish store with explicit types347interface FishState {348 fish: number349 addFish: () => void350}351352const useFishStore = create<FishState>()((set) => ({353 fish: 5,354 addFish: () => set((s) => ({ fish: s.fish + 1 })),355}))356357// In components, you can use both stores safely358function Zoo() {359 const { bears, addBear } = useBearStore()360 const { fish, addFish } = useFishStore()361362 return (363 <div>364 <div>365 {bears} bears and {fish} fish366 </div>367 <button onClick={addBear}>Add bear</button>368 <button onClick={addFish}>Add fish</button>369 </div>370 )371}372```373374### Conclusion375376Zustand together with TypeScript provides a balance: you keep the simplicity of small, minimalistic stores, while gaining the safety of strong typing.377You don’t need boilerplate or complex patterns - state and actions live side by side, fully typed, and ready to use.378Start with a basic store to learn the pattern, then expand gradually: use `combine` for cleaner inference, `persist` for storage, and `devtools` for debugging.
deleted:docs/guides/connect-to-state-with-url-hash.md-153 removed
1---2title: Connect to state with URL3nav: 114---56## Connect State with URL Hash78If you want to connect state of a store to URL hash, you can create your own hash storage.910```ts11import { create } from 'zustand'12import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'1314const hashStorage: StateStorage = {15 getItem: (key): string => {16 const searchParams = new URLSearchParams(location.hash.slice(1))17 const storedValue = searchParams.get(key) ?? ''18 return JSON.parse(storedValue)19 },20 setItem: (key, newValue): void => {21 const searchParams = new URLSearchParams(location.hash.slice(1))22 searchParams.set(key, JSON.stringify(newValue))23 location.hash = searchParams.toString()24 },25 removeItem: (key): void => {26 const searchParams = new URLSearchParams(location.hash.slice(1))27 searchParams.delete(key)28 location.hash = searchParams.toString()29 },30}3132export const useBoundStore = create()(33 persist(34 (set, get) => ({35 fishes: 0,36 addAFish: () => set({ fishes: get().fishes + 1 }),37 }),38 {39 name: 'food-storage', // unique name40 storage: createJSONStorage(() => hashStorage),41 },42 ),43)44```4546## Persist and Connect State with URL Parameters (Example: URL Query Parameters)4748There are times when you want to conditionally connect the state to the URL.49This example depicts usage of the URL query parameters50while keeping it synced with another persistence implementation, like `localstorage`.5152If you want the URL params to always populate, the conditional check on `getUrlSearch()` can be removed.5354The implementation below will update the URL in place, without refresh, as the relevant states change.5556```ts57import { create } from 'zustand'58import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'5960const getUrlSearch = () => {61 return window.location.search.slice(1)62}6364const persistentStorage: StateStorage = {65 getItem: (key): string => {66 // Check URL first67 if (getUrlSearch()) {68 const searchParams = new URLSearchParams(getUrlSearch())69 const storedValue = searchParams.get(key)70 return JSON.parse(storedValue as string)71 } else {72 // Otherwise, we should load from localstorage or alternative storage73 return JSON.parse(localStorage.getItem(key) as string)74 }75 },76 setItem: (key, newValue): void => {77 // Check if query params exist at all, can remove check if always want to set URL78 if (getUrlSearch()) {79 const searchParams = new URLSearchParams(getUrlSearch())80 searchParams.set(key, JSON.stringify(newValue))81 window.history.replaceState(null, '', `?${searchParams.toString()}`)82 }8384 localStorage.setItem(key, JSON.stringify(newValue))85 },86 removeItem: (key): void => {87 const searchParams = new URLSearchParams(getUrlSearch())88 searchParams.delete(key)89 window.location.search = searchParams.toString()90 },91}9293type LocalAndUrlStore = {94 typesOfFish: string[]95 addTypeOfFish: (fishType: string) => void96 numberOfBears: number97 setNumberOfBears: (newNumber: number) => void98}99100const storageOptions = {101 name: 'fishAndBearsStore',102 storage: createJSONStorage<LocalAndUrlStore>(() => persistentStorage),103}104105const useLocalAndUrlStore = create()(106 persist<LocalAndUrlStore>(107 (set) => ({108 typesOfFish: [],109 addTypeOfFish: (fishType) =>110 set((state) => ({ typesOfFish: [...state.typesOfFish, fishType] })),111112 numberOfBears: 0,113 setNumberOfBears: (numberOfBears) => set(() => ({ numberOfBears })),114 }),115 storageOptions,116 ),117)118119export default useLocalAndUrlStore120```121122When generating the URL from a component, you can call buildShareableUrl:123124```ts125const buildURLSuffix = (params, version = 0) => {126 const searchParams = new URLSearchParams()127128 const zustandStoreParams = {129 state: {130 typesOfFish: params.typesOfFish,131 numberOfBears: params.numberOfBears,132 },133 version: version, // version is here because that is included with how Zustand sets the state134 }135136 // The URL param key should match the name of the store, as specified as in storageOptions above137 searchParams.set('fishAndBearsStore', JSON.stringify(zustandStoreParams))138 return searchParams.toString()139}140141export const buildShareableUrl = (params, version) => {142 return `${window.location.origin}?${buildURLSuffix(params, version)}`143}144```145146The generated URL would look like (here without any encoding, for readability):147148`https://localhost/search?fishAndBearsStore={"state":{"typesOfFish":["tilapia","salmon"],"numberOfBears":15},"version":0}}`149150### Demo151152- Hash: https://stackblitz.com/edit/vitejs-vite-9vg24prg153- Query: https://stackblitz.com/edit/vitejs-vite-hyc97ynf
deleted:docs/guides/event-handler-in-pre-react-18.md-24 removed
deleted:docs/guides/flux-inspired-practice.md-77 removed
deleted:docs/guides/how-to-reset-state.md-45 removed
deleted:docs/guides/immutable-state-and-merging.md-59 removed
deleted:docs/guides/initialize-state-with-props.md-180 removed
1---2title: Initialize state with props3nav: 134---56In cases where [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) is needed, such as when a store should be initialized with props from a component, the recommended approach is to use a vanilla store with React.context.78## Store creator with `createStore`910```ts11import { createStore } from 'zustand'1213interface BearProps {14 bears: number15}1617interface BearState extends BearProps {18 addBear: () => void19}2021type BearStore = ReturnType<typeof createBearStore>2223const createBearStore = (initProps?: Partial<BearProps>) => {24 const DEFAULT_PROPS: BearProps = {25 bears: 0,26 }27 return createStore<BearState>()((set) => ({28 ...DEFAULT_PROPS,29 ...initProps,30 addBear: () => set((state) => ({ bears: ++state.bears })),31 }))32}33```3435## Creating a context with `React.createContext`3637```ts38import { createContext } from 'react'3940export const BearContext = createContext<BearStore | null>(null)41```4243## Basic component usage4445```tsx46// Provider implementation47import { useState } from 'react'4849function App() {50 const [store] = useState(() => createBearStore())51 return (52 <BearContext.Provider value={store}>53 <BasicConsumer />54 </BearContext.Provider>55 )56}57```5859```tsx60// Consumer component61import { useContext } from 'react'62import { useStore } from 'zustand'6364function BasicConsumer() {65 const store = useContext(BearContext)66 if (!store) throw new Error('Missing BearContext.Provider in the tree')6768 const bears = useStore(store, (s) => s.bears)69 const addBear = useStore(store, (s) => s.addBear)7071 return (72 <>73 <div>{bears} Bears.</div>74 <button onClick={addBear}>Add bear</button>75 </>76 )77}78```7980## Common patterns8182### Wrapping the context provider8384```tsx85// Provider wrapper86import { useState } from 'react'8788type BearProviderProps = React.PropsWithChildren<BearProps>8990function BearProvider({ children, ...props }: BearProviderProps) {91 const [store] = useState(() => createBearStore(props))92 return <BearContext.Provider value={store}>{children}</BearContext.Provider>93}94```9596### Extracting context logic into a custom hook9798```tsx99// Mimic the hook returned by `create`100import { useContext } from 'react'101import { useStore } from 'zustand'102103function useBearContext<T>(selector: (state: BearState) => T): T {104 const store = useContext(BearContext)105 if (!store) throw new Error('Missing BearContext.Provider in the tree')106 return useStore(store, selector)107}108```109110```tsx111// Consumer usage of the custom hook112function CommonConsumer() {113 const bears = useBearContext((s) => s.bears)114 const addBear = useBearContext((s) => s.addBear)115 return (116 <>117 <div>{bears} Bears.</div>118 <button onClick={addBear}>Add bear</button>119 </>120 )121}122```123124### Optionally use memoized selector for stable outputs125126```tsx127import { useShallow } from 'zustand/react/shallow'128129const meals = ['Salmon', 'Berries', 'Nuts']130131function CommonConsumer() {132 const bearMealsOrder = useBearContext(133 useShallow((s) =>134 Array.from({ length: s.bears }).map((_, index) =>135 meals.at(index % meals.length),136 ),137 ),138 )139 return (140 <>141 Order:142 <ul>143 {bearMealsOrder.map((meal) => (144 <li key={meal}>{meal}</li>145 ))}146 </ul>147 </>148 )149}150```151152### Optionally allow using a custom equality function153154```tsx155// Allow custom equality function by using useStoreWithEqualityFn instead of useStore156import { useContext } from 'react'157import { useStoreWithEqualityFn } from 'zustand/traditional'158159function useBearContext<T>(160 selector: (state: BearState) => T,161 equalityFn?: (left: T, right: T) => boolean,162): T {163 const store = useContext(BearContext)164 if (!store) throw new Error('Missing BearContext.Provider in the tree')165 return useStoreWithEqualityFn(store, selector, equalityFn)166}167```168169### Complete example170171```tsx172// Provider wrapper & custom hook consumer173function App2() {174 return (175 <BearProvider bears={2}>176 <HookConsumer />177 </BearProvider>178 )179}180```
deleted:docs/guides/maps-and-sets-usage.md-115 removed
1---2title: Map and Set Usage3nav: 104---56# Map and Set in Zustand78Map and Set are mutable data structures. To use them in Zustand, you must create new instances when updating.910## Map1112### Reading a Map1314```typescript15const foo = useSomeStore((state) => state.foo)16```1718### Updating a Map1920Always create a new Map instance:2122```ts23// Update single entry24set((state) => ({25 foo: new Map(state.foo).set(key, value),26}))2728// Delete entry29set((state) => {30 const next = new Map(state.foo)31 next.delete(key)32 return { foo: next }33})3435// Update multiple entries36set((state) => {37 const next = new Map(state.foo)38 next.set('key1', 'value1')39 next.set('key2', 'value2')40 return { foo: next }41})4243// Clear44set({ foo: new Map() })45```4647## Set4849### Reading a Set5051```ts52const bar = useSomeStore((state) => state.bar)53```5455### Updating a Set5657Always create a new Set instance:5859```ts60// Add item61set((state) => ({62 bar: new Set(state.bar).add(item),63}))6465// Delete item66set((state) => {67 const next = new Set(state.bar)68 next.delete(item)69 return { bar: next }70})7172// Toggle item73set((state) => {74 const next = new Set(state.bar)75 next.has(item) ? next.delete(item) : next.add(item)76 return { bar: next }77})7879// Clear80set({ bar: new Set() })81```8283## Why New Instances?8485Zustand detects changes by comparing references. Mutating a Map or Set doesn't change its reference:8687```ts88// ❌ Wrong - same reference, no re-render89set((state) => {90 state.foo.set(key, value)91 return { foo: state.foo }92})9394// ✅ Correct - new reference, triggers re-render95set((state) => ({96 foo: new Map(state.foo).set(key, value),97}))98```99100## Pitfall: Type Hints for Empty Collections101102Provide type hints when initializing empty Maps and Sets:103104```ts105{106 ids: new Set([] as string[]),107 users: new Map([] as [string, User][])108}109```110111Without type hints, TypeScript infers `never[]` which prevents adding items later.112113## Demos114115Basic: https://stackblitz.com/edit/vitejs-vite-5cu5ddvx
deleted:docs/guides/nextjs.md-316 removed
1---2title: Setup with Next.js3nav: 174---56> [!NOTE]7> We will be updating this guide soon based on our discussion in https://github.com/pmndrs/zustand/discussions/2740.89[Next.js](https://nextjs.org) is a popular server-side rendering framework for React that presents10some unique challenges for using Zustand properly.11Keep in mind that Zustand store is a global12variable (AKA module state) making it optional to use a `Context`.13These challenges include:1415- **Per-request store:** A Next.js server can handle multiple requests simultaneously. This means16 that the store should be created per request and should not be shared across requests.17- **SSR friendly:** Next.js applications are rendered twice, first on the server18 and again on the client. Having different outputs on both the client and the server will result19 in "hydration errors." The store will have to be initialized on the server and then20 re-initialized on the client with the same data in order to avoid that. Please read more about21 that in our [SSR and Hydration](./ssr-and-hydration.md) guide.22- **SPA routing friendly:** Next.js supports a hybrid model for client side routing, which means23 that in order to reset a store, we need to initialize it at the component level using a24 `Context`.25- **Server caching friendly:** Recent versions of Next.js (specifically applications using the App26 Router architecture) support aggressive server caching. Due to our store being a **module state**,27 it is completely compatible with this caching.2829We have these general recommendations for the appropriate use of Zustand:3031- **No global stores** - Because the store should not be shared across requests, it should not be defined32 as a global variable. Instead, the store should be created per request.33- **React Server Components should not read from or write to the store** - RSCs cannot use hooks or context. They aren't34 meant to be stateful. Having an RSC read from or write values to a global store violates the35 architecture of Next.js.3637### Creating a store per request3839Let's write our store factory function that will create a new store for each40request.4142```json43// tsconfig.json44{45 "compilerOptions": {46 "lib": ["dom", "dom.iterable", "esnext"],47 "allowJs": true,48 "skipLibCheck": true,49 "strict": true,50 "noEmit": true,51 "esModuleInterop": true,52 "module": "esnext",53 "moduleResolution": "bundler",54 "resolveJsonModule": true,55 "isolatedModules": true,56 "jsx": "preserve",57 "incremental": true,58 "plugins": [59 {60 "name": "next"61 }62 ],63 "paths": {64 "@/*": ["./src/*"]65 }66 },67 "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],68 "exclude": ["node_modules"]69}70```7172> **Note:** do not forget to remove all comments from your `tsconfig.json` file.7374### Initializing the store7576```ts77// src/stores/counter-store.ts78import { createStore } from 'zustand/vanilla'7980export type CounterState = {81 count: number82}8384export type CounterActions = {85 decrementCount: () => void86 incrementCount: () => void87}8889export type CounterStore = CounterState & CounterActions9091export const defaultInitState: CounterState = {92 count: 0,93}9495export const createCounterStore = (96 initState: CounterState = defaultInitState,97) => {98 return createStore<CounterStore>()((set) => ({99 ...initState,100 decrementCount: () => set((state) => ({ count: state.count - 1 })),101 incrementCount: () => set((state) => ({ count: state.count + 1 })),102 }))103}104```105106### Providing the store107108Let's use the `createCounterStore` in our component and share it using a context provider.109110```tsx111// src/providers/counter-store-provider.tsx112'use client'113114import { type ReactNode, createContext, useState, useContext } from 'react'115import { useStore } from 'zustand'116117import { type CounterStore, createCounterStore } from '@/stores/counter-store'118119export type CounterStoreApi = ReturnType<typeof createCounterStore>120121export const CounterStoreContext = createContext<CounterStoreApi | undefined>(122 undefined,123)124125export interface CounterStoreProviderProps {126 children: ReactNode127}128129export const CounterStoreProvider = ({130 children,131}: CounterStoreProviderProps) => {132 const [store] = useState(() => createCounterStore())133 return (134 <CounterStoreContext.Provider value={store}>135 {children}136 </CounterStoreContext.Provider>137 )138}139140export const useCounterStore = <T,>(141 selector: (store: CounterStore) => T,142): T => {143 const counterStoreContext = useContext(CounterStoreContext)144 if (!counterStoreContext) {145 throw new Error(`useCounterStore must be used within CounterStoreProvider`)146 }147148 return useStore(counterStoreContext, selector)149}150```151152> **Note:** In this example, we ensure that this component is re-render-safe by checking the153> value of the reference, so that the store is only created once. This component will only be154> rendered once per request on the server, but might be re-rendered multiple times on the client if155> there are stateful client components located above this component in the tree, or if this component156> also contains other mutable state that causes a re-render.157158### Using the store with different architectures159160There are two architectures for a Next.js application: the161[Pages Router](https://nextjs.org/docs/pages/building-your-application/routing) and the162[App Router](https://nextjs.org/docs/app/building-your-application/routing). The usage of Zustand on163both architectures should be the same with slight differences related to each architecture.164165#### Pages Router166167```tsx168// src/components/pages/home-page.tsx169import { useCounterStore } from '@/providers/counter-store-provider'170171export const HomePage = () => {172 const { count, incrementCount, decrementCount } = useCounterStore(173 (state) => state,174 )175176 return (177 <div>178 Count: {count}179 <hr />180 <button type="button" onClick={incrementCount}>181 Increment Count182 </button>183 <button type="button" onClick={decrementCount}>184 Decrement Count185 </button>186 </div>187 )188}189```190191```tsx192// src/_app.tsx193import type { AppProps } from 'next/app'194195import { CounterStoreProvider } from '@/providers/counter-store-provider'196197export default function App({ Component, pageProps }: AppProps) {198 return (199 <CounterStoreProvider>200 <Component {...pageProps} />201 </CounterStoreProvider>202 )203}204```205206```tsx207// src/pages/index.tsx208import { HomePage } from '@/components/pages/home-page'209210export default function Home() {211 return <HomePage />212}213```214215> **Note:** creating a store per route would require creating and sharing the store216> at page (route) component level. Try not to use this if you do not need to create217> a store per route.218219```tsx220// src/pages/index.tsx221import { CounterStoreProvider } from '@/providers/counter-store-provider'222import { HomePage } from '@/components/pages/home-page'223224export default function Home() {225 return (226 <CounterStoreProvider>227 <HomePage />228 </CounterStoreProvider>229 )230}231```232233#### App Router234235```tsx236// src/components/pages/home-page.tsx237'use client'238239import { useCounterStore } from '@/providers/counter-store-provider'240241export const HomePage = () => {242 const { count, incrementCount, decrementCount } = useCounterStore(243 (state) => state,244 )245246 return (247 <div>248 Count: {count}249 <hr />250 <button type="button" onClick={incrementCount}>251 Increment Count252 </button>253 <button type="button" onClick={decrementCount}>254 Decrement Count255 </button>256 </div>257 )258}259```260261```tsx262// src/app/layout.tsx263import type { Metadata } from 'next'264import { Inter } from 'next/font/google'265import './globals.css'266267import { CounterStoreProvider } from '@/providers/counter-store-provider'268269const inter = Inter({ subsets: ['latin'] })270271export const metadata: Metadata = {272 title: 'Create Next App',273 description: 'Generated by create next app',274}275276export default function RootLayout({277 children,278}: Readonly<{279 children: React.ReactNode280}>) {281 return (282 <html lang="en">283 <body className={inter.className}>284 <CounterStoreProvider>{children}</CounterStoreProvider>285 </body>286 </html>287 )288}289```290291```tsx292// src/app/page.tsx293import { HomePage } from '@/components/pages/home-page'294295export default function Home() {296 return <HomePage />297}298```299300> **Note:** creating a store per route would require creating and sharing the store301> at page (route) component level. Try not to use this if you do not need to create302> a store per route.303304```tsx305// src/app/page.tsx306import { CounterStoreProvider } from '@/providers/counter-store-provider'307import { HomePage } from '@/components/pages/home-page'308309export default function Home() {310 return (311 <CounterStoreProvider>312 <HomePage />313 </CounterStoreProvider>314 )315}316```
deleted:docs/guides/practice-with-no-store-actions.md-42 removed
1---2title: Practice with no store actions3nav: 64---56The recommended usage is to colocate actions and states within the store (let your actions be located together with your state).78For example:910```js11export const useBoundStore = create((set) => ({12 count: 0,13 text: 'hello',14 inc: () => set((state) => ({ count: state.count + 1 })),15 setText: (text) => set({ text }),16}))17```1819This creates a self-contained store with data and actions together.2021---2223An alternative approach is to define actions at module level, external to the store.2425```js26export const useBoundStore = create(() => ({27 count: 0,28 text: 'hello',29}))3031export const inc = () =>32 useBoundStore.setState((state) => ({ count: state.count + 1 }))3334export const setText = (text) => useBoundStore.setState({ text })35```3637This has a few advantages:3839- It doesn't require a hook to call an action;40- It facilitates code splitting.4142While this pattern doesn't offer any downsides, some may prefer colocating due to its encapsulated nature.
deleted:docs/guides/prevent-rerenders-with-use-shallow.md-63 removed
1---2title: Prevent rerenders with useShallow3nav: 154---56When you need to subscribe to a computed state from a store, the recommended way is to7use a selector.89The computed selector will cause a rerender if the output has changed according to [Object.is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is?retiredLocale=it).1011In this case you might want to use `useShallow` to avoid a rerender if the computed value is always shallow12equal the previous one.1314## Example1516We have a store that associates to each bear a meal and we want to render their names.1718```js19import { create } from 'zustand'2021const useMeals = create(() => ({22 papaBear: 'large porridge-pot',23 mamaBear: 'middle-size porridge pot',24 littleBear: 'A little, small, wee pot',25}))2627export const BearNames = () => {28 const names = useMeals((state) => Object.keys(state))2930 return <div>{names.join(', ')}</div>31}32```3334Now papa bear wants a pizza instead:3536```js37useMeals.setState({38 papaBear: 'a large pizza',39})40```4142This change causes `BearNames` rerenders even though the actual output of `names` has not changed according to shallow equal.4344We can fix that using `useShallow`!4546```js47import { create } from 'zustand'48import { useShallow } from 'zustand/react/shallow'4950const useMeals = create(() => ({51 papaBear: 'large porridge-pot',52 mamaBear: 'middle-size porridge pot',53 littleBear: 'A little, small, wee pot',54}))5556export const BearNames = () => {57 const names = useMeals(useShallow((state) => Object.keys(state)))5859 return <div>{names.join(', ')}</div>60}61```6263Now they can all order other meals without causing unnecessary rerenders of our `BearNames` component.
deleted:docs/guides/slices-pattern.md-120 removed
1---2title: Slices Pattern3nav: 144---56## Slicing the store into smaller stores78Your store can become bigger and bigger and tougher to maintain as you add more features.910You can divide your main store into smaller individual stores to achieve modularity. This is simple to accomplish in Zustand!1112The first individual store:1314```js15export const createFishSlice = (set) => ({16 fishes: 0,17 addFish: () => set((state) => ({ fishes: state.fishes + 1 })),18})19```2021Another individual store:2223```js24export const createBearSlice = (set) => ({25 bears: 0,26 addBear: () => set((state) => ({ bears: state.bears + 1 })),27 eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),28})29```3031You can now combine both the stores into **one bounded store**:3233```js34import { create } from 'zustand'35import { createBearSlice } from './bearSlice'36import { createFishSlice } from './fishSlice'3738export const useBoundStore = create((...a) => ({39 ...createBearSlice(...a),40 ...createFishSlice(...a),41}))42```4344### Usage in a React component4546```jsx47import { useBoundStore } from './stores/useBoundStore'4849function App() {50 const bears = useBoundStore((state) => state.bears)51 const fishes = useBoundStore((state) => state.fishes)52 const addBear = useBoundStore((state) => state.addBear)53 return (54 <div>55 <h2>Number of bears: {bears}</h2>56 <h2>Number of fishes: {fishes}</h2>57 <button onClick={() => addBear()}>Add a bear</button>58 </div>59 )60}6162export default App63```6465### Updating multiple stores6667You can update multiple stores, at the same time, in a single function.6869```js70export const createBearFishSlice = (set, get) => ({71 addBearAndFish: () => {72 get().addBear()73 get().addFish()74 },75})76```7778Combining all the stores together is the same as before.7980```js81import { create } from 'zustand'82import { createBearSlice } from './bearSlice'83import { createFishSlice } from './fishSlice'84import { createBearFishSlice } from './createBearFishSlice'8586export const useBoundStore = create((...a) => ({87 ...createBearSlice(...a),88 ...createFishSlice(...a),89 ...createBearFishSlice(...a),90}))91```9293## Adding middlewares9495Adding middlewares to a combined store is the same as with other normal stores.9697Adding [`persist` middleware](../integrations/persisting-store-data.md) to our `useBoundStore`:9899```js100import { create } from 'zustand'101import { createBearSlice } from './bearSlice'102import { createFishSlice } from './fishSlice'103import { persist } from 'zustand/middleware'104105export const useBoundStore = create(106 persist(107 (...a) => ({108 ...createBearSlice(...a),109 ...createFishSlice(...a),110 }),111 { name: 'bound-store' },112 ),113)114```115116Please keep in mind you should only apply middlewares in the combined store. Applying them inside individual slices can lead to unexpected issues.117118## Usage with TypeScript119120A detailed guide on how to use the slice pattern in Zustand with TypeScript can be found [here](./advanced-typescript.md#slices-pattern).
deleted:docs/guides/ssr-and-hydration.md-198 removed
1---2title: SSR and Hydration3nav: 164---56## Server-side Rendering (SSR)78Server-side Rendering (SSR) is a technique that helps us render our components into9HTML strings on the server, send them directly to the browser, and finally "hydrate" the10static markup into a fully interactive app on the client.1112### React1314Let's say we want to render a stateless app using React. In order to do that, we need15to use `express`, `react` and `react-dom/server`. We don't need `react-dom/client`16since it's a stateless app.1718Let's dive into that:1920- `express` helps us build a web app that we can run using Node,21- `react` helps us build the UI components that we use in our app,22- `react-dom/server` helps us render our components on a server.2324```json25// tsconfig.json26{27 "compilerOptions": {28 "noImplicitAny": false,29 "noEmitOnError": true,30 "removeComments": false,31 "sourceMap": true,32 "target": "esnext"33 },34 "include": ["**/*"]35}36```3738> **Note:** do not forget to remove all comments from your `tsconfig.json` file.3940```tsx41// app.tsx42export const App = () => {43 return (44 <html>45 <head>46 <meta charSet="utf-8" />47 <meta name="viewport" content="width=device-width, initial-scale=1" />48 <title>Static Server-side-rendered App</title>49 </head>50 <body>51 <div>Hello World!</div>52 </body>53 </html>54 )55}56```5758```tsx59// server.tsx60import express from 'express'61import React from 'react'62import ReactDOMServer from 'react-dom/server'6364import { App } from './app.tsx'6566const port = Number.parseInt(process.env.PORT || '3000', 10)67const app = express()6869app.get('/', (_, res) => {70 const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {71 onShellReady() {72 res.setHeader('content-type', 'text/html')73 pipe(res)74 },75 })76})7778app.listen(port, () => {79 console.log(`Server is listening at ${port}`)80})81```8283```sh84tsc --build85```8687```sh88node server.js89```9091## Hydration9293Hydration turns the initial HTML snapshot from the server into a fully interactive app94that runs in the browser. The right way to "hydrate" a component is by using `hydrateRoot`.9596### React9798Let's say we want to render a stateful app using React. In order to do that we need to99use `express`, `react`, `react-dom/server` and `react-dom/client`.100101Let's dive into that:102103- `express` helps us build a web app that we can run using Node,104- `react` helps us build the UI components that we use in our app,105- `react-dom/server` helps us render our components on a server,106- `react-dom/client` helps us hydrate our components on a client.107108> **Note:** Do not forget that even if we can render our components on a server, it is109> important to "hydrate" them on a client to make them interactive.110111```json112// tsconfig.json113{114 "compilerOptions": {115 "noImplicitAny": false,116 "noEmitOnError": true,117 "removeComments": false,118 "sourceMap": true,119 "target": "esnext"120 },121 "include": ["**/*"]122}123```124125> **Note:** do not forget to remove all comments in your `tsconfig.json` file.126127```tsx128// app.tsx129export const App = () => {130 return (131 <html>132 <head>133 <meta charSet="utf-8" />134 <meta name="viewport" content="width=device-width, initial-scale=1" />135 <title>Static Server-side-rendered App</title>136 </head>137 <body>138 <div>Hello World!</div>139 </body>140 </html>141 )142}143```144145```tsx146// main.tsx147import ReactDOMClient from 'react-dom/client'148149import { App } from './app.tsx'150151ReactDOMClient.hydrateRoot(document, <App />)152```153154```tsx155// server.tsx156import express from 'express'157import React from 'react'158import ReactDOMServer from 'react-dom/server'159160import { App } from './app.tsx'161162const port = Number.parseInt(process.env.PORT || '3000', 10)163const app = express()164165app.use('/', (_, res) => {166 const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {167 bootstrapScripts: ['/main.js'],168 onShellReady() {169 res.setHeader('content-type', 'text/html')170 pipe(res)171 },172 })173})174175app.listen(port, () => {176 console.log(`Server is listening at ${port}`)177})178```179180```sh181tsc --build182```183184```sh185node server.js186```187188> **Warning:** The React tree you pass to `hydrateRoot` needs to produce the same output as it did on the server.189> The most common causes leading to hydration errors include:190>191> - Extra whitespace (like newlines) around the React-generated HTML inside the root node.192> - Using checks like typeof window !== 'undefined' in your rendering logic.193> - Using browser-only APIs like `window.matchMedia` in your rendering logic.194> - Rendering different data on the server and the client.195>196> React recovers from some hydration errors, but you must fix them like other bugs. In the best case, they’ll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.197198You can read more about the caveats and pitfalls here: [hydrateRoot](https://react.dev/reference/react-dom/client/hydrateRoot)
deleted:docs/guides/testing.md-741 removed
1---2title: Testing3description: Writing Tests4nav: 85---67## Setting Up a Test Environment89### Test Runners1011Usually, your test runner needs to be configured to run JavaScript/TypeScript syntax. If you're12going to be testing UI components, you will likely need to configure the test runner to use JSDOM13to provide a mock DOM environment.1415See these resources for test runner configuration instructions:1617- **Jest**18 - [Jest: Getting Started](https://jestjs.io/docs/getting-started)19 - [Jest: Configuration - Test Environment](https://jestjs.io/docs/configuration#testenvironment-string)20- **Vitest**21 - [Vitest: Getting Started](https://vitest.dev/guide)22 - [Vitest: Configuration - Test Environment](https://vitest.dev/config/#environment)2324### UI and Network Testing Tools2526**We recommend using [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)27to test out React components that connect to Zustand**. RTL is a simple and complete React DOM28testing utility that encourages good testing practices. It uses ReactDOM's `render` function and29`act` from `react-dom/tests-utils`. Furthermore, [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)30is the alternative to RTL to test out React Native components. The [Testing Library](https://testing-library.com/)31family of tools also includes adapters for many other popular frameworks.3233We also recommend using [Mock Service Worker (MSW)](https://mswjs.io/) to mock network requests, as34this means your application logic does not need to be changed or mocked when writing tests.3536- **React Testing Library (DOM)**37 - [DOM Testing Library: Setup](https://testing-library.com/docs/dom-testing-library/setup)38 - [React Testing Library: Setup](https://testing-library.com/docs/react-testing-library/setup)39 - [Testing Library Jest-DOM Matchers](https://testing-library.com/docs/ecosystem-jest-dom)40- **Native Testing Library (React Native)**41 - [Native Testing Library: Setup](https://testing-library.com/docs/react-native-testing-library/setup)42- **User Event Testing Library (DOM)**43 - [User Event Testing Library: Setup](https://testing-library.com/docs/user-event/setup)44- **TypeScript for Jest**45 - [TypeScript for Jest: Setup](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation)46- **TypeScript for Node**47 - [TypeScript for Node: Setup](https://typestrong.org/ts-node/docs/installation)48- **Mock Service Worker**49 - [MSW: Installation](https://mswjs.io/docs/getting-started/install)50 - [MSW: Setting up mock requests](https://mswjs.io/docs/getting-started/mocks/rest-api)51 - [MSW: Mock server configuration for Node](https://mswjs.io/docs/getting-started/integrate/node)5253## Setting Up Zustand for testing5455> **Note**: Since Jest and Vitest have slight differences, like Vitest using **ES modules** and Jest using56> **CommonJS modules**, you need to keep that in mind if you are using Vitest instead of Jest.5758The mock provided below will enable the relevant test runner to reset the zustand stores after each test.5960### Shared code just for testing purposes6162This shared code was added to avoid code duplication in our demo since we use the same counter store63creator for both implementations, with and without `Context` API — `createStore` and `create`, respectively.6465```ts66// shared/counter-store-creator.ts67import { type StateCreator } from 'zustand'6869export type CounterStore = {70 count: number71 inc: () => void72}7374export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({75 count: 1,76 inc: () => set((state) => ({ count: state.count + 1 })),77})78```7980### Jest8182In the next steps we are going to setup our Jest environment in order to mock Zustand.8384```ts85// __mocks__/zustand.ts86import { act } from '@testing-library/react'87import type * as ZustandExportedTypes from 'zustand'88export * from 'zustand'8990const { create: actualCreate, createStore: actualCreateStore } =91 jest.requireActual<typeof ZustandExportedTypes>('zustand')9293// a variable to hold reset functions for all stores declared in the app94export const storeResetFns = new Set<() => void>()9596const createUncurried = <T>(97 stateCreator: ZustandExportedTypes.StateCreator<T>,98) => {99 const store = actualCreate(stateCreator)100 const initialState = store.getInitialState()101 storeResetFns.add(() => {102 store.setState(initialState, true)103 })104 return store105}106107// when creating a store, we get its initial state, create a reset function and add it in the set108export const create = (<T>(109 stateCreator: ZustandExportedTypes.StateCreator<T>,110) => {111 console.log('zustand create mock')112113 // to support curried version of create114 return typeof stateCreator === 'function'115 ? createUncurried(stateCreator)116 : createUncurried117}) as typeof ZustandExportedTypes.create118119const createStoreUncurried = <T>(120 stateCreator: ZustandExportedTypes.StateCreator<T>,121) => {122 const store = actualCreateStore(stateCreator)123 const initialState = store.getInitialState()124 storeResetFns.add(() => {125 store.setState(initialState, true)126 })127 return store128}129130// when creating a store, we get its initial state, create a reset function and add it in the set131export const createStore = (<T>(132 stateCreator: ZustandExportedTypes.StateCreator<T>,133) => {134 console.log('zustand createStore mock')135136 // to support curried version of createStore137 return typeof stateCreator === 'function'138 ? createStoreUncurried(stateCreator)139 : createStoreUncurried140}) as typeof ZustandExportedTypes.createStore141142// reset all stores after each test run143afterEach(() => {144 act(() => {145 storeResetFns.forEach((resetFn) => {146 resetFn()147 })148 })149})150```151152```ts153// setup-jest.ts154import '@testing-library/jest-dom'155```156157```ts158// jest.config.ts159import type { JestConfigWithTsJest } from 'ts-jest'160161const config: JestConfigWithTsJest = {162 preset: 'ts-jest',163 testEnvironment: 'jsdom',164 setupFilesAfterEnv: ['./setup-jest.ts'],165}166167export default config168```169170> **Note**: to use TypeScript we need to install two packages `ts-jest` and `ts-node`.171172### Vitest173174In the next steps we are going to setup our Vitest environment in order to mock Zustand.175176> **Warning:** In Vitest you can change the [root](https://vitest.dev/config/#root).177> Due to that, you need make sure that you are creating your `__mocks__` directory in the right place.178> Let's say that you change the **root** to `./src`, that means you need to create a `__mocks__`179> directory under `./src`. The end result would be `./src/__mocks__`, rather than `./__mocks__`.180> Creating `__mocks__` directory in the wrong place can lead to issues when using Vitest.181182```ts183// __mocks__/zustand.ts184import { act } from '@testing-library/react'185import type * as ZustandExportedTypes from 'zustand'186export * from 'zustand'187188const { create: actualCreate, createStore: actualCreateStore } =189 await vi.importActual<typeof ZustandExportedTypes>('zustand')190191// a variable to hold reset functions for all stores declared in the app192export const storeResetFns = new Set<() => void>()193194const createUncurried = <T>(195 stateCreator: ZustandExportedTypes.StateCreator<T>,196) => {197 const store = actualCreate(stateCreator)198 const initialState = store.getInitialState()199 storeResetFns.add(() => {200 store.setState(initialState, true)201 })202 return store203}204205// when creating a store, we get its initial state, create a reset function and add it in the set206export const create = (<T>(207 stateCreator: ZustandExportedTypes.StateCreator<T>,208) => {209 console.log('zustand create mock')210211 // to support curried version of create212 return typeof stateCreator === 'function'213 ? createUncurried(stateCreator)214 : createUncurried215}) as typeof ZustandExportedTypes.create216217const createStoreUncurried = <T>(218 stateCreator: ZustandExportedTypes.StateCreator<T>,219) => {220 const store = actualCreateStore(stateCreator)221 const initialState = store.getInitialState()222 storeResetFns.add(() => {223 store.setState(initialState, true)224 })225 return store226}227228// when creating a store, we get its initial state, create a reset function and add it in the set229export const createStore = (<T>(230 stateCreator: ZustandExportedTypes.StateCreator<T>,231) => {232 console.log('zustand createStore mock')233234 // to support curried version of createStore235 return typeof stateCreator === 'function'236 ? createStoreUncurried(stateCreator)237 : createStoreUncurried238}) as typeof ZustandExportedTypes.createStore239240// reset all stores after each test run241afterEach(() => {242 act(() => {243 storeResetFns.forEach((resetFn) => {244 resetFn()245 })246 })247})248```249250> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need251> to add `import { afterEach, vi } from 'vitest'` at the top.252253```ts254// global.d.ts255/// <reference types="vite/client" />256/// <reference types="vitest/globals" />257```258259> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we do260> need to remove `/// <reference types="vitest/globals" />`.261262```ts263// setup-vitest.ts264import '@testing-library/jest-dom/vitest'265266vi.mock('zustand') // to make it work like Jest (auto-mocking)267```268269> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need270> to add `import { vi } from 'vitest'` at the top.271272```ts273// vitest.config.ts274import { defineConfig, mergeConfig } from 'vitest/config'275import viteConfig from './vite.config'276277export default defineConfig((configEnv) =>278 mergeConfig(279 viteConfig(configEnv),280 defineConfig({281 test: {282 globals: true,283 environment: 'jsdom',284 setupFiles: ['./setup-vitest.ts'],285 },286 }),287 ),288)289```290291### Testing Components292293In the next examples we are going to use `useCounterStore`294295> **Note**: all of these examples are written using TypeScript.296297```ts298// shared/counter-store-creator.ts299import { type StateCreator } from 'zustand'300301export type CounterStore = {302 count: number303 inc: () => void304}305306export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({307 count: 1,308 inc: () => set((state) => ({ count: state.count + 1 })),309})310```311312```ts313// stores/use-counter-store.ts314import { create } from 'zustand'315316import {317 type CounterStore,318 counterStoreCreator,319} from '../shared/counter-store-creator'320321export const useCounterStore = create<CounterStore>()(counterStoreCreator)322```323324```tsx325// contexts/use-counter-store-context.tsx326import { type ReactNode, createContext, useContext, useState } from 'react'327import { createStore } from 'zustand'328import { useStoreWithEqualityFn } from 'zustand/traditional'329import { shallow } from 'zustand/shallow'330331import {332 type CounterStore,333 counterStoreCreator,334} from '../shared/counter-store-creator'335336export const createCounterStore = () => {337 return createStore<CounterStore>(counterStoreCreator)338}339340export type CounterStoreApi = ReturnType<typeof createCounterStore>341342export const CounterStoreContext = createContext<CounterStoreApi | undefined>(343 undefined,344)345346export interface CounterStoreProviderProps {347 children: ReactNode348}349350export const CounterStoreProvider = ({351 children,352}: CounterStoreProviderProps) => {353 const [store] = useState(() => createCounterStore())354 return (355 <CounterStoreContext.Provider value={store}>356 {children}357 </CounterStoreContext.Provider>358 )359}360361export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T362363export const useCounterStoreContext = <T,>(364 selector: UseCounterStoreContextSelector<T>,365): T => {366 const counterStoreContext = useContext(CounterStoreContext)367368 if (counterStoreContext === undefined) {369 throw new Error(370 'useCounterStoreContext must be used within CounterStoreProvider',371 )372 }373374 return useStoreWithEqualityFn(counterStoreContext, selector, shallow)375}376```377378```tsx379// components/counter/counter.tsx380import { useCounterStore } from '../../stores/use-counter-store'381382export function Counter() {383 const { count, inc } = useCounterStore()384385 return (386 <div>387 <h2>Counter Store</h2>388 <h4>{count}</h4>389 <button onClick={inc}>One Up</button>390 </div>391 )392}393```394395```ts396// components/counter/index.ts397export * from './counter'398```399400```tsx401// components/counter/counter.test.tsx402import { act, render, screen } from '@testing-library/react'403import userEvent from '@testing-library/user-event'404405import { Counter } from './counter'406407describe('Counter', () => {408 test('should render with initial state of 1', async () => {409 renderCounter()410411 expect(await screen.findByText(/^1$/)).toBeInTheDocument()412 expect(413 await screen.findByRole('button', { name: /one up/i }),414 ).toBeInTheDocument()415 })416417 test('should increase count by clicking a button', async () => {418 const user = userEvent.setup()419420 renderCounter()421422 expect(await screen.findByText(/^1$/)).toBeInTheDocument()423424 await user.click(await screen.findByRole('button', { name: /one up/i }))425426 expect(await screen.findByText(/^2$/)).toBeInTheDocument()427 })428})429430const renderCounter = () => {431 return render(<Counter />)432}433```434435```tsx436// components/counter-with-context/counter-with-context.tsx437import {438 CounterStoreProvider,439 useCounterStoreContext,440} from '../../contexts/use-counter-store-context'441442const Counter = () => {443 const { count, inc } = useCounterStoreContext((state) => state)444445 return (446 <div>447 <h2>Counter Store Context</h2>448 <h4>{count}</h4>449 <button onClick={inc}>One Up</button>450 </div>451 )452}453454export const CounterWithContext = () => {455 return (456 <CounterStoreProvider>457 <Counter />458 </CounterStoreProvider>459 )460}461```462463```tsx464// components/counter-with-context/index.ts465export * from './counter-with-context'466```467468```tsx469// components/counter-with-context/counter-with-context.test.tsx470import { act, render, screen } from '@testing-library/react'471import userEvent from '@testing-library/user-event'472473import { CounterWithContext } from './counter-with-context'474475describe('CounterWithContext', () => {476 test('should render with initial state of 1', async () => {477 renderCounterWithContext()478479 expect(await screen.findByText(/^1$/)).toBeInTheDocument()480 expect(481 await screen.findByRole('button', { name: /one up/i }),482 ).toBeInTheDocument()483 })484485 test('should increase count by clicking a button', async () => {486 const user = userEvent.setup()487488 renderCounterWithContext()489490 expect(await screen.findByText(/^1$/)).toBeInTheDocument()491492 await user.click(await screen.findByRole('button', { name: /one up/i }))493494 expect(await screen.findByText(/^2$/)).toBeInTheDocument()495 })496})497498const renderCounterWithContext = () => {499 return render(<CounterWithContext />)500}501```502503> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need504> to add `import { describe, test, expect } from 'vitest'` at the top of each test file.505506### Testing Stores507508In the next examples we are going to use `useCounterStore`509510> **Note**: all of these examples are written using TypeScript.511512```ts513// shared/counter-store-creator.ts514import { type StateCreator } from 'zustand'515516export type CounterStore = {517 count: number518 inc: () => void519}520521export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({522 count: 1,523 inc: () => set((state) => ({ count: state.count + 1 })),524})525```526527```ts528// stores/use-counter-store.ts529import { create } from 'zustand'530531import {532 type CounterStore,533 counterStoreCreator,534} from '../shared/counter-store-creator'535536export const useCounterStore = create<CounterStore>()(counterStoreCreator)537```538539```tsx540// contexts/use-counter-store-context.tsx541import { type ReactNode, createContext, useContext, useState } from 'react'542import { createStore } from 'zustand'543import { useStoreWithEqualityFn } from 'zustand/traditional'544import { shallow } from 'zustand/shallow'545546import {547 type CounterStore,548 counterStoreCreator,549} from '../shared/counter-store-creator'550551export const createCounterStore = () => {552 return createStore<CounterStore>(counterStoreCreator)553}554555export type CounterStoreApi = ReturnType<typeof createCounterStore>556557export const CounterStoreContext = createContext<CounterStoreApi | undefined>(558 undefined,559)560561export interface CounterStoreProviderProps {562 children: ReactNode563}564565export const CounterStoreProvider = ({566 children,567}: CounterStoreProviderProps) => {568 const [store] = useState(() => createCounterStore())569 return (570 <CounterStoreContext.Provider value={store}>571 {children}572 </CounterStoreContext.Provider>573 )574}575576export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T577578export const useCounterStoreContext = <T,>(579 selector: UseCounterStoreContextSelector<T>,580): T => {581 const counterStoreContext = useContext(CounterStoreContext)582583 if (counterStoreContext === undefined) {584 throw new Error(585 'useCounterStoreContext must be used within CounterStoreProvider',586 )587 }588589 return useStoreWithEqualityFn(counterStoreContext, selector, shallow)590}591```592593```tsx594// components/counter/counter.tsx595import { useCounterStore } from '../../stores/use-counter-store'596597export function Counter() {598 const { count, inc } = useCounterStore()599600 return (601 <div>602 <h2>Counter Store</h2>603 <h4>{count}</h4>604 <button onClick={inc}>One Up</button>605 </div>606 )607}608```609610```ts611// components/counter/index.ts612export * from './counter'613```614615```tsx616// components/counter/counter.test.tsx617import { act, render, screen } from '@testing-library/react'618import userEvent from '@testing-library/user-event'619620import { Counter, useCounterStore } from '../../../stores/use-counter-store.ts'621622describe('Counter', () => {623 test('should render with initial state of 1', async () => {624 renderCounter()625626 expect(useCounterStore.getState().count).toBe(1)627 })628629 test('should increase count by clicking a button', async () => {630 const user = userEvent.setup()631632 renderCounter()633634 expect(useCounterStore.getState().count).toBe(1)635636 await user.click(await screen.findByRole('button', { name: /one up/i }))637638 expect(useCounterStore.getState().count).toBe(2)639 })640})641642const renderCounter = () => {643 return render(<Counter />)644}645```646647```tsx648// components/counter-with-context/counter-with-context.tsx649import {650 CounterStoreProvider,651 useCounterStoreContext,652} from '../../contexts/use-counter-store-context'653654const Counter = () => {655 const { count, inc } = useCounterStoreContext((state) => state)656657 return (658 <div>659 <h2>Counter Store Context</h2>660 <h4>{count}</h4>661 <button onClick={inc}>One Up</button>662 </div>663 )664}665666export const CounterWithContext = () => {667 return (668 <CounterStoreProvider>669 <Counter />670 </CounterStoreProvider>671 )672}673```674675```tsx676// components/counter-with-context/index.ts677export * from './counter-with-context'678```679680```tsx681// components/counter-with-context/counter-with-context.test.tsx682import { act, render, screen } from '@testing-library/react'683import userEvent from '@testing-library/user-event'684685import { CounterStoreContext } from '../../../contexts/use-counter-store-context'686import { counterStoreCreator } from '../../../shared/counter-store-creator'687688describe('CounterWithContext', () => {689 test('should render with initial state of 1', async () => {690 const counterStore = counterStoreCreator()691692 renderCounterWithContext(counterStore)693694 expect(counterStore.getState().count).toBe(1)695 expect(696 await screen.findByRole('button', { name: /one up/i }),697 ).toBeInTheDocument()698 })699700 test('should increase count by clicking a button', async () => {701 const user = userEvent.setup()702 const counterStore = counterStoreCreator()703704 renderCounterWithContext(counterStore)705706 expect(counterStore.getState().count).toBe(1)707708 await user.click(await screen.findByRole('button', { name: /one up/i }))709710 expect(counterStore.getState().count).toBe(2)711 })712})713714const renderCounterWithContext = (store) => {715 return render(<CounterWithContext />, {716 wrapper: ({ children }) => (717 <CounterStoreContext.Provider value={store}>718 {children}719 </CounterStoreContext.Provider>720 ),721 })722}723```724725## References726727- **React Testing Library**: [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)728 is a very lightweight solution for testing React components. It provides utility functions on top729 of `react-dom` and `react-dom/test-utils`, in a way that encourages better testing practices. Its730 primary guiding principle is: "The more your tests resemble the way your software is used, the731 more confidence they can give you."732- **Native Testing Library**: [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)733 is a very lightweight solution for testing React Native components, similarly to RTL, but its734 functions are built on top of `react-test-renderer`.735- **Testing Implementation Details**: Blog post by Kent C. Dodds on why he recommends to avoid736 [testing implementation details](https://kentcdodds.com/blog/testing-implementation-details).737738## Demos739740- Jest: https://stackblitz.com/edit/jest-zustand741- Vitest: https://stackblitz.com/edit/vitest-zustand
deleted:docs/guides/tutorial-tic-tac-toe.md-1429 removed
1---2title: 'Tutorial: Tic-Tac-Toe'3description: Building a game4nav: 15---67# Tutorial: Tic-Tac-Toe89## Building a game1011You will build a small tic-tac-toe game during this tutorial. This tutorial does assume existing12React knowledge. The techniques you'll learn in the tutorial are fundamental to building any React13app, and fully understanding it will give you a deep understanding of React and Zustand.1415> [!NOTE]16> This tutorial is crafted for those who learn best through hands-on experience and want to swiftly17> create something tangible. It draws inspiration from React's tic-tac-toe tutorial.1819The tutorial is divided into several sections:2021- Setup for the tutorial will give you a starting point to follow the tutorial.22- Overview will teach you the fundamentals of React: components, props, and state.23- Completing the game will teach you the most common techniques in React development.24- Adding time travel will give you a deeper insight into the unique strengths of React.2526### What are you building?2728In this tutorial, you'll build an interactive tic-tac-toe game with React and Zustand.2930You can see what it will look like when you're finished here:3132```jsx33import { create } from 'zustand'34import { combine } from 'zustand/middleware'3536const useGameStore = create(37 combine(38 {39 history: [Array(9).fill(null)],40 currentMove: 0,41 },42 (set, get) => {43 return {44 setHistory: (nextHistory) => {45 set((state) => ({46 history:47 typeof nextHistory === 'function'48 ? nextHistory(state.history)49 : nextHistory,50 }))51 },52 setCurrentMove: (nextCurrentMove) => {53 set((state) => ({54 currentMove:55 typeof nextCurrentMove === 'function'56 ? nextCurrentMove(state.currentMove)57 : nextCurrentMove,58 }))59 },60 }61 },62 ),63)6465function Square({ value, onSquareClick }) {66 return (67 <button68 style={{69 display: 'inline-flex',70 alignItems: 'center',71 justifyContent: 'center',72 padding: 0,73 backgroundColor: '#fff',74 border: '1px solid #999',75 outline: 0,76 borderRadius: 0,77 fontSize: '1rem',78 fontWeight: 'bold',79 }}80 onClick={onSquareClick}81 >82 {value}83 </button>84 )85}8687function Board({ xIsNext, squares, onPlay }) {88 const winner = calculateWinner(squares)89 const turns = calculateTurns(squares)90 const player = xIsNext ? 'X' : 'O'91 const status = calculateStatus(winner, turns, player)9293 function handleClick(i) {94 if (squares[i] || winner) return95 const nextSquares = squares.slice()96 nextSquares[i] = player97 onPlay(nextSquares)98 }99100 return (101 <>102 <div style={{ marginBottom: '0.5rem' }}>{status}</div>103 <div104 style={{105 display: 'grid',106 gridTemplateColumns: 'repeat(3, 1fr)',107 gridTemplateRows: 'repeat(3, 1fr)',108 width: 'calc(3 * 2.5rem)',109 height: 'calc(3 * 2.5rem)',110 border: '1px solid #999',111 }}112 >113 {squares.map((_, i) => (114 <Square115 key={`square-${i}`}116 value={squares[i]}117 onSquareClick={() => handleClick(i)}118 />119 ))}120 </div>121 </>122 )123}124125export default function Game() {126 const history = useGameStore((state) => state.history)127 const setHistory = useGameStore((state) => state.setHistory)128 const currentMove = useGameStore((state) => state.currentMove)129 const setCurrentMove = useGameStore((state) => state.setCurrentMove)130 const xIsNext = currentMove % 2 === 0131 const currentSquares = history[currentMove]132133 function handlePlay(nextSquares) {134 const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]135 setHistory(nextHistory)136 setCurrentMove(nextHistory.length - 1)137 }138139 function jumpTo(nextMove) {140 setCurrentMove(nextMove)141 }142143 return (144 <div145 style={{146 display: 'flex',147 flexDirection: 'row',148 fontFamily: 'monospace',149 }}150 >151 <div>152 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />153 </div>154 <div style={{ marginLeft: '1rem' }}>155 <ol>156 {history.map((_, historyIndex) => {157 const description =158 historyIndex > 0159 ? `Go to move #${historyIndex}`160 : 'Go to game start'161162 return (163 <li key={historyIndex}>164 <button onClick={() => jumpTo(historyIndex)}>165 {description}166 </button>167 </li>168 )169 })}170 </ol>171 </div>172 </div>173 )174}175176function calculateWinner(squares) {177 const lines = [178 [0, 1, 2],179 [3, 4, 5],180 [6, 7, 8],181 [0, 3, 6],182 [1, 4, 7],183 [2, 5, 8],184 [0, 4, 8],185 [2, 4, 6],186 ]187188 for (let i = 0; i < lines.length; i++) {189 const [a, b, c] = lines[i]190 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {191 return squares[a]192 }193 }194195 return null196}197198function calculateTurns(squares) {199 return squares.filter((square) => !square).length200}201202function calculateStatus(winner, turns, player) {203 if (!winner && !turns) return 'Draw'204 if (winner) return `Winner ${winner}`205 return `Next player: ${player}`206}207```208209### Building the board210211Let's start by creating the `Square` component, which will be a building block for our `Board`212component. This component will represent each square in our game.213214The `Square` component should take `value` and `onSquareClick` as props. It should return a215`<button>` element, styled to look like a square. The button displays the value prop, which can be216`'X'`, `'O'`, or `null`, depending on the game's state. When the button is clicked, it triggers the217`onSquareClick` function passed in as a prop, allowing the game to respond to user input.218219Here's the code for the `Square` component:220221```jsx222function Square({ value, onSquareClick }) {223 return (224 <button225 style={{226 display: 'inline-flex',227 alignItems: 'center',228 justifyContent: 'center',229 padding: 0,230 backgroundColor: '#fff',231 border: '1px solid #999',232 outline: 0,233 borderRadius: 0,234 fontSize: '1rem',235 fontWeight: 'bold',236 }}237 onClick={onSquareClick}238 >239 {value}240 </button>241 )242}243```244245Let's move on to creating the Board component, which will consist of 9 squares arranged in a grid.246This component will serve as the main playing area for our game.247248The `Board` component should return a `<div>` element styled as a grid. The grid layout is achieved249using CSS Grid, with three columns and three rows, each taking up an equal fraction of the available250space. The overall size of the grid is determined by the width and height properties, ensuring that251it is square-shaped and appropriately sized.252253Inside the grid, we place nine Square components, each with a value prop representing its position.254These Square components will eventually hold the game symbols (`'X'` or `'O'`) and handle user255interactions.256257Here's the code for the `Board` component:258259```jsx260export default function Board() {261 return (262 <div263 style={{264 display: 'grid',265 gridTemplateColumns: 'repeat(3, 1fr)',266 gridTemplateRows: 'repeat(3, 1fr)',267 width: 'calc(3 * 2.5rem)',268 height: 'calc(3 * 2.5rem)',269 border: '1px solid #999',270 }}271 >272 <Square value="1" />273 <Square value="2" />274 <Square value="3" />275 <Square value="4" />276 <Square value="5" />277 <Square value="6" />278 <Square value="7" />279 <Square value="8" />280 <Square value="9" />281 </div>282 )283}284```285286This Board component sets up the basic structure for our game board by arranging nine squares in a2873x3 grid. It positions the squares neatly, providing a foundation for adding more features and288handling player interactions in the future.289290### Lifting state up291292Each `Square` component could maintain a part of the game's state. To check for a winner in a293tic-tac-toe game, the `Board` component would need to somehow know the state of each of the 9294`Square` components.295296How would you approach that? At first, you might guess that the `Board` component needs to ask each297`Square` component for that `Square`'s component state. Although this approach is technically298possible in React, we discourage it because the code becomes difficult to understand, susceptible299to bugs, and hard to refactor. Instead, the best approach is to store the game's state in the300parent `Board` component instead of in each `Square` component. The `Board` component can tell each301`Square` component what to display by passing a prop, like you did when you passed a number to each302`Square` component.303304> [!IMPORTANT]305> To collect data from multiple children, or to have two or more child components306> communicate with each other, declare the shared state in their parent component instead. The307> parent component can pass that state back down to the children via props. This keeps the child308> components in sync with each other and with their parent.309310Let's take this opportunity to try it out. Edit the `Board` component so that it declares a state311variable named squares that defaults to an array of 9 nulls corresponding to the 9 squares:312313```jsx314import { create } from 'zustand'315import { combine } from 'zustand/middleware'316317const useGameStore = create(318 combine({ squares: Array(9).fill(null) }, (set) => {319 return {320 setSquares: (nextSquares) => {321 set((state) => ({322 squares:323 typeof nextSquares === 'function'324 ? nextSquares(state.squares)325 : nextSquares,326 }))327 },328 }329 }),330)331332export default function Board() {333 const squares = useGameStore((state) => state.squares)334 const setSquares = useGameStore((state) => state.setSquares)335336 return (337 <div338 style={{339 display: 'grid',340 gridTemplateColumns: 'repeat(3, 1fr)',341 gridTemplateRows: 'repeat(3, 1fr)',342 width: 'calc(3 * 2.5rem)',343 height: 'calc(3 * 2.5rem)',344 border: '1px solid #999',345 }}346 >347 {squares.map((square, squareIndex) => (348 <Square key={squareIndex} value={square} />349 ))}350 </div>351 )352}353```354355`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The356`useGameStore` declares a `squares` state that's initially set to that array. Each entry in the357array corresponds to the value of a square. When you fill the board in later, the squares array358will look like this:359360```js361const squares = ['O', null, 'X', 'X', 'X', 'O', 'O', null, null]362```363364Each Square will now receive a `value` prop that will either be `'X'`, `'O'`, or `null` for empty365squares.366367Next, you need to change what happens when a `Square` component is clicked. The `Board` component368now maintains which squares are filled. You'll need to create a way for the `Square` component to369update the `Board`'s component state. Since state is private to a component that defines it, you370cannot update the `Board`'s component state directly from `Square` component.371372Instead, you'll pass down a function from the Board component to the `Square` component, and you'll373have `Square` component call that function when a square is clicked. You'll start with the function374that the `Square` component will call when it is clicked. You'll call that function `onSquareClick`:375376Now you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name377`handleClick`. To connect `onSquareClick` to `handleClick` you'll pass an inline function to the378`onSquareClick` prop of the first Square component:379380```jsx381<Square key={squareIndex} value={square} onSquareClick={() => handleClick(i)} />382```383384Lastly, you will define the `handleClick` function inside the `Board` component to update the385squares array holding your board's state.386387The `handleClick` function should take the index of the square to update and create a copy of the388`squares` array (`nextSquares`). Then, `handleClick` updates the `nextSquares` array by adding `X`389to the square at the specified index (`i`) if is not already filled.390391```jsx {5-10,27}392export default function Board() {393 const squares = useGameStore((state) => state.squares)394 const setSquares = useGameStore((state) => state.setSquares)395396 function handleClick(i) {397 if (squares[i]) return398 const nextSquares = squares.slice()399 nextSquares[i] = 'X'400 setSquares(nextSquares)401 }402403 return (404 <div405 style={{406 display: 'grid',407 gridTemplateColumns: 'repeat(3, 1fr)',408 gridTemplateRows: 'repeat(3, 1fr)',409 width: 'calc(3 * 2.5rem)',410 height: 'calc(3 * 2.5rem)',411 border: '1px solid #999',412 }}413 >414 {squares.map((square, squareIndex) => (415 <Square416 key={squareIndex}417 value={square}418 onSquareClick={() => handleClick(squareIndex)}419 />420 ))}421 </div>422 )423}424```425426> [!IMPORTANT]427> Note how in `handleClick` function, you call `.slice()` to create a copy of the squares array428> instead of modifying the existing array.429430### Taking turns431432It's now time to fix a major defect in this tic-tac-toe game: the `'O'`s cannot be used on the433board.434435You'll set the first move to be `'X'` by default. Let's keep track of this by adding another piece436of state to the `useGameStore` hook:437438```jsx {2,12-18}439const useGameStore = create(440 combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {441 return {442 setSquares: (nextSquares) => {443 set((state) => ({444 squares:445 typeof nextSquares === 'function'446 ? nextSquares(state.squares)447 : nextSquares,448 }))449 },450 setXIsNext: (nextXIsNext) => {451 set((state) => ({452 xIsNext:453 typeof nextXIsNext === 'function'454 ? nextXIsNext(state.xIsNext)455 : nextXIsNext,456 }))457 },458 }459 }),460)461```462463Each time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next464and the game's state will be saved. You'll update the Board's `handleClick` function to flip the465value of `xIsNext`:466467```jsx {2-3,6,11}468export default function Board() {469 const xIsNext = useGameStore((state) => state.xIsNext)470 const setXIsNext = useGameStore((state) => state.setXIsNext)471 const squares = useGameStore((state) => state.squares)472 const setSquares = useGameStore((state) => state.setSquares)473 const player = xIsNext ? 'X' : 'O'474475 function handleClick(i) {476 if (squares[i]) return477 const nextSquares = squares.slice()478 nextSquares[i] = player479 setSquares(nextSquares)480 setXIsNext(!xIsNext)481 }482483 return (484 <div485 style={{486 display: 'grid',487 gridTemplateColumns: 'repeat(3, 1fr)',488 gridTemplateRows: 'repeat(3, 1fr)',489 width: 'calc(3 * 2.5rem)',490 height: 'calc(3 * 2.5rem)',491 border: '1px solid #999',492 }}493 >494 {squares.map((square, squareIndex) => (495 <Square496 key={squareIndex}497 value={square}498 onSquareClick={() => handleClick(squareIndex)}499 />500 ))}501 </div>502 )503}504```505506### Declaring a winner or draw507508Now that the players can take turns, you'll want to show when the game is won or drawn and there509are no more turns to make. To do this you'll add three helper functions. The first helper function510called `calculateWinner` that takes an array of 9 squares, checks for a winner and returns `'X'`,511`'O'`, or `null` as appropriate. The second helper function called `calculateTurns` that takes the512same array, checks for remaining turns by filtering out only `null` items, and returns the count of513them. The last helper called `calculateStatus` that takes the remaining turns, the winner, and the514current player (`'X' or 'O'`):515516```js517function calculateWinner(squares) {518 const lines = [519 [0, 1, 2],520 [3, 4, 5],521 [6, 7, 8],522 [0, 3, 6],523 [1, 4, 7],524 [2, 5, 8],525 [0, 4, 8],526 [2, 4, 6],527 ]528529 for (let i = 0; i < lines.length; i++) {530 const [a, b, c] = lines[i]531 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {532 return squares[a]533 }534 }535536 return null537}538539function calculateTurns(squares) {540 return squares.filter((square) => !square).length541}542543function calculateStatus(winner, turns, player) {544 if (!winner && !turns) return 'Draw'545 if (winner) return `Winner ${winner}`546 return `Next player: ${player}`547}548```549550You will use the result of `calculateWinner(squares)` in the Board component's `handleClick`551function to check if a player has won. You can perform this check at the same time you check if a552user has clicked a square that already has a `'X'` or and `'O'`. We'd like to return early in553both cases:554555```js {2}556function handleClick(i) {557 if (squares[i] || winner) return558 const nextSquares = squares.slice()559 nextSquares[i] = player560 setSquares(nextSquares)561 setXIsNext(!xIsNext)562}563```564565To let the players know when the game is over, you can display text such as `'Winner: X'` or566`'Winner: O'`. To do that you'll add a `status` section to the `Board` component. The status will567display the winner or draw if the game is over and if the game is ongoing you'll display which568player's turn is next:569570```jsx {6-7,9,21}571export default function Board() {572 const xIsNext = useGameStore((state) => state.xIsNext)573 const setXIsNext = useGameStore((state) => state.setXIsNext)574 const squares = useGameStore((state) => state.squares)575 const setSquares = useGameStore((state) => state.setSquares)576 const winner = calculateWinner(squares)577 const turns = calculateTurns(squares)578 const player = xIsNext ? 'X' : 'O'579 const status = calculateStatus(winner, turns, player)580581 function handleClick(i) {582 if (squares[i] || winner) return583 const nextSquares = squares.slice()584 nextSquares[i] = player585 setSquares(nextSquares)586 setXIsNext(!xIsNext)587 }588589 return (590 <>591 <div style={{ marginBottom: '0.5rem' }}>{status}</div>592 <div593 style={{594 display: 'grid',595 gridTemplateColumns: 'repeat(3, 1fr)',596 gridTemplateRows: 'repeat(3, 1fr)',597 width: 'calc(3 * 2.5rem)',598 height: 'calc(3 * 2.5rem)',599 border: '1px solid #999',600 }}601 >602 {squares.map((square, squareIndex) => (603 <Square604 key={squareIndex}605 value={square}606 onSquareClick={() => handleClick(squareIndex)}607 />608 ))}609 </div>610 </>611 )612}613```614615Congratulations! You now have a working tic-tac-toe game. And you've just learned the basics of616React and Zustand too. So you are the real winner here. Here is what the code should look like:617618```jsx619import { create } from 'zustand'620import { combine } from 'zustand/middleware'621622const useGameStore = create(623 combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {624 return {625 setSquares: (nextSquares) => {626 set((state) => ({627 squares:628 typeof nextSquares === 'function'629 ? nextSquares(state.squares)630 : nextSquares,631 }))632 },633 setXIsNext: (nextXIsNext) => {634 set((state) => ({635 xIsNext:636 typeof nextXIsNext === 'function'637 ? nextXIsNext(state.xIsNext)638 : nextXIsNext,639 }))640 },641 }642 }),643)644645function Square({ value, onSquareClick }) {646 return (647 <button648 style={{649 display: 'inline-flex',650 alignItems: 'center',651 justifyContent: 'center',652 padding: 0,653 backgroundColor: '#fff',654 border: '1px solid #999',655 outline: 0,656 borderRadius: 0,657 fontSize: '1rem',658 fontWeight: 'bold',659 }}660 onClick={onSquareClick}661 >662 {value}663 </button>664 )665}666667export default function Board() {668 const xIsNext = useGameStore((state) => state.xIsNext)669 const setXIsNext = useGameStore((state) => state.setXIsNext)670 const squares = useGameStore((state) => state.squares)671 const setSquares = useGameStore((state) => state.setSquares)672 const winner = calculateWinner(squares)673 const turns = calculateTurns(squares)674 const player = xIsNext ? 'X' : 'O'675 const status = calculateStatus(winner, turns, player)676677 function handleClick(i) {678 if (squares[i] || winner) return679 const nextSquares = squares.slice()680 nextSquares[i] = player681 setSquares(nextSquares)682 setXIsNext(!xIsNext)683 }684685 return (686 <>687 <div style={{ marginBottom: '0.5rem' }}>{status}</div>688 <div689 style={{690 display: 'grid',691 gridTemplateColumns: 'repeat(3, 1fr)',692 gridTemplateRows: 'repeat(3, 1fr)',693 width: 'calc(3 * 2.5rem)',694 height: 'calc(3 * 2.5rem)',695 border: '1px solid #999',696 }}697 >698 {squares.map((square, squareIndex) => (699 <Square700 key={squareIndex}701 value={square}702 onSquareClick={() => handleClick(squareIndex)}703 />704 ))}705 </div>706 </>707 )708}709710function calculateWinner(squares) {711 const lines = [712 [0, 1, 2],713 [3, 4, 5],714 [6, 7, 8],715 [0, 3, 6],716 [1, 4, 7],717 [2, 5, 8],718 [0, 4, 8],719 [2, 4, 6],720 ]721722 for (let i = 0; i < lines.length; i++) {723 const [a, b, c] = lines[i]724 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {725 return squares[a]726 }727 }728729 return null730}731732function calculateTurns(squares) {733 return squares.filter((square) => !square).length734}735736function calculateStatus(winner, turns, player) {737 if (!winner && !turns) return 'Draw'738 if (winner) return `Winner ${winner}`739 return `Next player: ${player}`740}741```742743### Adding time travel744745As a final exercise, let's make it possible to “go back in time” and revisit previous moves in the746game.747748If you had directly modified the squares array, implementing this time-travel feature would be very749difficult. However, since you used `slice()` to create a new copy of the squares array after every750move, treating it as immutable, you can store every past version of the squares array and navigate751between them.752753You'll keep track of these past squares arrays in a new state variable called `history`. This754`history` array will store all board states, from the first move to the latest one, and will look755something like this:756757```js758const history = [759 // First move760 [null, null, null, null, null, null, null, null, null],761 // Second move762 ['X', null, null, null, null, null, null, null, null],763 // Third move764 ['X', 'O', null, null, null, null, null, null, null],765 // and so on...766]767```768769This approach allows you to easily navigate between different game states and implement the770time-travel feature.771772### Lifting state up, again773774Next, you will create a new top-level component called `Game` to display a list of past moves. This775is where you will store the `history` state that contains the entire game history.776777By placing the `history` state in the `Game` component, you can remove the `squares` state from the778`Board` component. You will now lift the state up from the `Board` component to the top-level `Game`779component. This change allows the `Game` component to have full control over the `Board`'s780component data and instruct the `Board` component to render previous turns from the `history`.781782First, add a `Game` component with `export default` and remove it from `Board` component. Here is783what the code should look like:784785```jsx {1,44-61}786function Board() {787 const xIsNext = useGameStore((state) => state.xIsNext)788 const setXIsNext = useGameStore((state) => state.setXIsNext)789 const squares = useGameStore((state) => state.squares)790 const setSquares = useGameStore((state) => state.setSquares)791 const winner = calculateWinner(squares)792 const turns = calculateTurns(squares)793 const player = xIsNext ? 'X' : 'O'794 const status = calculateStatus(winner, turns, player)795796 function handleClick(i) {797 if (squares[i] || winner) return798 const nextSquares = squares.slice()799 nextSquares[i] = player800 setSquares(nextSquares)801 setXIsNext(!xIsNext)802 }803804 return (805 <>806 <div style={{ marginBottom: '0.5rem' }}>{status}</div>807 <div808 style={{809 display: 'grid',810 gridTemplateColumns: 'repeat(3, 1fr)',811 gridTemplateRows: 'repeat(3, 1fr)',812 width: 'calc(3 * 2.5rem)',813 height: 'calc(3 * 2.5rem)',814 border: '1px solid #999',815 }}816 >817 {squares.map((square, squareIndex) => (818 <Square819 key={squareIndex}820 value={square}821 onSquareClick={() => handleClick(squareIndex)}822 />823 ))}824 </div>825 </>826 )827}828829export default function Game() {830 return (831 <div832 style={{833 display: 'flex',834 flexDirection: 'row',835 fontFamily: 'monospace',836 }}837 >838 <div>839 <Board />840 </div>841 <div style={{ marginLeft: '1rem' }}>842 <ol>{/* TODO */}</ol>843 </div>844 </div>845 )846}847```848849Add some state to the `useGameStore` hook to track the history of moves:850851```js {2,4-11}852const useGameStore = create(853 combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {854 return {855 setHistory: (nextHistory) => {856 set((state) => ({857 history:858 typeof nextHistory === 'function'859 ? nextHistory(state.history)860 : nextHistory,861 }))862 },863 setXIsNext: (nextXIsNext) => {864 set((state) => ({865 xIsNext:866 typeof nextXIsNext === 'function'867 ? nextXIsNext(state.xIsNext)868 : nextXIsNext,869 }))870 },871 }872 }),873)874```875876Notice how `[Array(9).fill(null)]` creates an array with a single item, which is itself an array of8779 null values.878879To render the squares for the current move, you'll need to read the most recent squares array from880the `history` state. You don't need an extra state for this because you already have enough881information to calculate it during rendering:882883```jsx {2-6}884export default function Game() {885 const history = useGameStore((state) => state.history)886 const setHistory = useGameStore((state) => state.setHistory)887 const xIsNext = useGameStore((state) => state.xIsNext)888 const setXIsNext = useGameStore((state) => state.setXIsNext)889 const currentSquares = history[history.length - 1]890891 return (892 <div893 style={{894 display: 'flex',895 flexDirection: 'row',896 fontFamily: 'monospace',897 }}898 >899 <div>900 <Board />901 </div>902 <div style={{ marginLeft: '1rem' }}>903 <ol>{/*TODO*/}</ol>904 </div>905 </div>906 )907}908```909910Next, create a `handlePlay` function inside the `Game` component that will be called by the `Board`911component to update the game. Pass `xIsNext`, `currentSquares` and `handlePlay` as props to the912`Board` component:913914```jsx {8-10,21}915export default function Game() {916 const history = useGameStore((state) => state.history)917 const setHistory = useGameStore((state) => state.setHistory)918 const xIsNext = useGameStore((state) => state.xIsNext)919 const setXIsNext = useGameStore((state) => state.setXIsNext)920 const currentSquares = history[history.length - 1]921922 function handlePlay(nextSquares) {923 // TODO924 }925926 return (927 <div928 style={{929 display: 'flex',930 flexDirection: 'row',931 fontFamily: 'monospace',932 }}933 >934 <div>935 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />936 </div>937 <div style={{ marginLeft: '1rem' }}>938 <ol>{/*TODO*/}</ol>939 </div>940 </div>941 )942}943```944945Let's make the `Board` component fully controlled by the props it receives. To do this, we'll modify946the `Board` component to accept three props: `xIsNext`, `squares`, and a new `onPlay` function that947the `Board` component can call with the updated squares array when a player makes a move.948949```jsx {1}950function Board({ xIsNext, squares, onPlay }) {951 const winner = calculateWinner(squares)952 const turns = calculateTurns(squares)953 const player = xIsNext ? 'X' : 'O'954 const status = calculateStatus(winner, turns, player)955956 function handleClick(i) {957 if (squares[i] || winner) return958 const nextSquares = squares.slice()959 nextSquares[i] = player960 onPlay(nextSquares)961 }962963 return (964 <>965 <div style={{ marginBottom: '0.5rem' }}>{status}</div>966 <div967 style={{968 display: 'grid',969 gridTemplateColumns: 'repeat(3, 1fr)',970 gridTemplateRows: 'repeat(3, 1fr)',971 width: 'calc(3 * 2.5rem)',972 height: 'calc(3 * 2.5rem)',973 border: '1px solid #999',974 }}975 >976 {squares.map((square, squareIndex) => (977 <Square978 key={squareIndex}979 value={square}980 onSquareClick={() => handleClick(squareIndex)}981 />982 ))}983 </div>984 </>985 )986}987```988989The `Board` component is now fully controlled by the props passed to it by the `Game` component. To990get the game working again, you need to implement the `handlePlay` function in the `Game`991component.992993What should `handlePlay` do when called? Previously, the `Board` component called `setSquares` with994an updated array; now it passes the updated squares array to `onPlay`.995996The `handlePlay` function needs to update the `Game` component's state to trigger a re-render.997Instead of using `setSquares`, you'll update the `history` state variable by appending the updated998squares array as a new `history` entry. You also need to toggle `xIsNext`, just as the `Board`999component used1000to do.10011002```js {2-3}1003function handlePlay(nextSquares) {1004 setHistory(history.concat([nextSquares]))1005 setXIsNext(!xIsNext)1006}1007```10081009At this point, you've moved the state to live in the `Game` component, and the UI should be fully1010working, just as it was before the refactor. Here is what the code should look like at this point:10111012```jsx1013import { create } from 'zustand'1014import { combine } from 'zustand/middleware'10151016const useGameStore = create(1017 combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {1018 return {1019 setHistory: (nextHistory) => {1020 set((state) => ({1021 history:1022 typeof nextHistory === 'function'1023 ? nextHistory(state.history)1024 : nextHistory,1025 }))1026 },1027 setXIsNext: (nextXIsNext) => {1028 set((state) => ({1029 xIsNext:1030 typeof nextXIsNext === 'function'1031 ? nextXIsNext(state.xIsNext)1032 : nextXIsNext,1033 }))1034 },1035 }1036 }),1037)10381039function Square({ value, onSquareClick }) {1040 return (1041 <button1042 style={{1043 display: 'inline-flex',1044 alignItems: 'center',1045 justifyContent: 'center',1046 padding: 0,1047 backgroundColor: '#fff',1048 border: '1px solid #999',1049 outline: 0,1050 borderRadius: 0,1051 fontSize: '1rem',1052 fontWeight: 'bold',1053 }}1054 onClick={onSquareClick}1055 >1056 {value}1057 </button>1058 )1059}10601061function Board({ xIsNext, squares, onPlay }) {1062 const winner = calculateWinner(squares)1063 const turns = calculateTurns(squares)1064 const player = xIsNext ? 'X' : 'O'1065 const status = calculateStatus(winner, turns, player)10661067 function handleClick(i) {1068 if (squares[i] || winner) return1069 const nextSquares = squares.slice()1070 nextSquares[i] = player1071 onPlay(nextSquares)1072 }10731074 return (1075 <>1076 <div style={{ marginBottom: '0.5rem' }}>{status}</div>1077 <div1078 style={{1079 display: 'grid',1080 gridTemplateColumns: 'repeat(3, 1fr)',1081 gridTemplateRows: 'repeat(3, 1fr)',1082 width: 'calc(3 * 2.5rem)',1083 height: 'calc(3 * 2.5rem)',1084 border: '1px solid #999',1085 }}1086 >1087 {squares.map((square, squareIndex) => (1088 <Square1089 key={squareIndex}1090 value={square}1091 onSquareClick={() => handleClick(squareIndex)}1092 />1093 ))}1094 </div>1095 </>1096 )1097}10981099export default function Game() {1100 const history = useGameStore((state) => state.history)1101 const setHistory = useGameStore((state) => state.setHistory)1102 const xIsNext = useGameStore((state) => state.xIsNext)1103 const setXIsNext = useGameStore((state) => state.setXIsNext)1104 const currentSquares = history[history.length - 1]11051106 function handlePlay(nextSquares) {1107 setHistory(history.concat([nextSquares]))1108 setXIsNext(!xIsNext)1109 }11101111 return (1112 <div1113 style={{1114 display: 'flex',1115 flexDirection: 'row',1116 fontFamily: 'monospace',1117 }}1118 >1119 <div>1120 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1121 </div>1122 <div style={{ marginLeft: '1rem' }}>1123 <ol>{/*TODO*/}</ol>1124 </div>1125 </div>1126 )1127}11281129function calculateWinner(squares) {1130 const lines = [1131 [0, 1, 2],1132 [3, 4, 5],1133 [6, 7, 8],1134 [0, 3, 6],1135 [1, 4, 7],1136 [2, 5, 8],1137 [0, 4, 8],1138 [2, 4, 6],1139 ]11401141 for (let i = 0; i < lines.length; i++) {1142 const [a, b, c] = lines[i]1143 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {1144 return squares[a]1145 }1146 }11471148 return null1149}11501151function calculateTurns(squares) {1152 return squares.filter((square) => !square).length1153}11541155function calculateStatus(winner, turns, player) {1156 if (!winner && !turns) return 'Draw'1157 if (winner) return `Winner ${winner}`1158 return `Next player: ${player}`1159}1160```11611162### Showing the past moves11631164Since you are recording the tic-tac-toe game's history, you can now display a list of past moves to1165the player.11661167You already have an array of `history` moves in store, so now you need to transform it to an array1168of React elements. In JavaScript, to transform one array into another, you can use the Array1169`.map()` method:11701171You'll use `map` to transform your `history` of moves into React elements representing buttons on the1172screen, and display a list of buttons to **jump** to past moves. Let's `map` over the `history` in1173the `Game` component:11741175```jsx {29-44}1176export default function Game() {1177 const history = useGameStore((state) => state.history)1178 const setHistory = useGameStore((state) => state.setHistory)1179 const xIsNext = useGameStore((state) => state.xIsNext)1180 const setXIsNext = useGameStore((state) => state.setXIsNext)1181 const currentSquares = history[history.length - 1]11821183 function handlePlay(nextSquares) {1184 setHistory(history.concat([nextSquares]))1185 setXIsNext(!xIsNext)1186 }11871188 function jumpTo(nextMove) {1189 // TODO1190 }11911192 return (1193 <div1194 style={{1195 display: 'flex',1196 flexDirection: 'row',1197 fontFamily: 'monospace',1198 }}1199 >1200 <div>1201 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1202 </div>1203 <div style={{ marginLeft: '1rem' }}>1204 <ol>1205 {history.map((_, historyIndex) => {1206 const description =1207 historyIndex > 01208 ? `Go to move #${historyIndex}`1209 : 'Go to game start'12101211 return (1212 <li key={historyIndex}>1213 <button onClick={() => jumpTo(historyIndex)}>1214 {description}1215 </button>1216 </li>1217 )1218 })}1219 </ol>1220 </div>1221 </div>1222 )1223}1224```12251226Before you can implement the `jumpTo` function, you need the `Game` component to keep track of which1227step the user is currently viewing. To do this, define a new state variable called `currentMove`,1228which will start at `0`:12291230```js {3,14-21}1231const useGameStore = create(1232 combine(1233 { history: [Array(9).fill(null)], currentMove: 0, xIsNext: true },1234 (set) => {1235 return {1236 setHistory: (nextHistory) => {1237 set((state) => ({1238 history:1239 typeof nextHistory === 'function'1240 ? nextHistory(state.history)1241 : nextHistory,1242 }))1243 },1244 setCurrentMove: (nextCurrentMove) => {1245 set((state) => ({1246 currentMove:1247 typeof nextCurrentMove === 'function'1248 ? nextCurrentMove(state.currentMove)1249 : nextCurrentMove,1250 }))1251 },1252 setXIsNext: (nextXIsNext) => {1253 set((state) => ({1254 xIsNext:1255 typeof nextXIsNext === 'function'1256 ? nextXIsNext(state.xIsNext)1257 : nextXIsNext,1258 }))1259 },1260 }1261 },1262 ),1263)1264```12651266Next, update the `jumpTo` function inside `Game` component to update that `currentMove`. You’ll1267also set `xIsNext` to `true` if the number that you’re changing `currentMove` to is even.12681269```js {2-3}1270function jumpTo(nextMove) {1271 setCurrentMove(nextMove)1272 setXIsNext(currentMove % 2 === 0)1273}1274```12751276You will now make two changes to the `handlePlay` function in the `Game` component, which is called1277when you click on a square.12781279- If you "go back in time" and then make a new move from that point, you only want to keep the1280 history up to that point. Instead of adding `nextSquares` after all items in the history (using1281 the Array `.concat()` method), you'll add it after all items in1282 `history.slice(0, currentMove + 1)` to keep only that portion of the old history.1283- Each time a move is made, you need to update `currentMove` to point to the latest history entry.12841285```js {2-4}1286function handlePlay(nextSquares) {1287 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1288 setHistory(nextHistory)1289 setCurrentMove(nextHistory.length - 1)1290 setXIsNext(!xIsNext)1291}1292```12931294Finally, you will modify the `Game` component to render the currently selected move, instead of1295always rendering the final move:12961297```jsx {2-8}1298export default function Game() {1299 const history = useGameStore((state) => state.history)1300 const setHistory = useGameStore((state) => state.setHistory)1301 const currentMove = useGameStore((state) => state.currentMove)1302 const setCurrentMove = useGameStore((state) => state.setCurrentMove)1303 const xIsNext = useGameStore((state) => state.xIsNext)1304 const setXIsNext = useGameStore((state) => state.setXIsNext)1305 const currentSquares = history[currentMove]13061307 function handlePlay(nextSquares) {1308 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1309 setHistory(nextHistory)1310 setCurrentMove(nextHistory.length - 1)1311 setXIsNext(!xIsNext)1312 }13131314 function jumpTo(nextMove) {1315 setCurrentMove(nextMove)1316 setXIsNext(nextMove % 2 === 0)1317 }13181319 return (1320 <div1321 style={{1322 display: 'flex',1323 flexDirection: 'row',1324 fontFamily: 'monospace',1325 }}1326 >1327 <div>1328 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1329 </div>1330 <div style={{ marginLeft: '1rem' }}>1331 <ol>1332 {history.map((_, historyIndex) => {1333 const description =1334 historyIndex > 01335 ? `Go to move #${historyIndex}`1336 : 'Go to game start'13371338 return (1339 <li key={historyIndex}>1340 <button onClick={() => jumpTo(historyIndex)}>1341 {description}1342 </button>1343 </li>1344 )1345 })}1346 </ol>1347 </div>1348 </div>1349 )1350}1351```13521353### Final cleanup13541355If you look closely at the code, you'll see that `xIsNext` is `true` when `currentMove` is even and1356`false` when `currentMove` is odd. This means that if you know the value of `currentMove`, you can1357always determine what `xIsNext` should be.13581359There's no need to store `xIsNext` separately in the state. It’s better to avoid redundant state1360because it can reduce bugs and make your code easier to understand. Instead, you can calculate1361`xIsNext` based on `currentMove`:13621363```jsx {2-5,13,17}1364export default function Game() {1365 const history = useGameStore((state) => state.history)1366 const setHistory = useGameStore((state) => state.setHistory)1367 const currentMove = useGameStore((state) => state.currentMove)1368 const setCurrentMove = useGameStore((state) => state.setCurrentMove)1369 const xIsNext = currentMove % 2 === 01370 const currentSquares = history[currentMove]13711372 function handlePlay(nextSquares) {1373 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1374 setHistory(nextHistory)1375 setCurrentMove(nextHistory.length - 1)1376 }13771378 function jumpTo(nextMove) {1379 setCurrentMove(nextMove)1380 }13811382 return (1383 <div1384 style={{1385 display: 'flex',1386 flexDirection: 'row',1387 fontFamily: 'monospace',1388 }}1389 >1390 <div>1391 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1392 </div>1393 <div style={{ marginLeft: '1rem' }}>1394 <ol>1395 {history.map((_, historyIndex) => {1396 const description =1397 historyIndex > 01398 ? `Go to move #${historyIndex}`1399 : 'Go to game start'14001401 return (1402 <li key={historyIndex}>1403 <button onClick={() => jumpTo(historyIndex)}>1404 {description}1405 </button>1406 </li>1407 )1408 })}1409 </ol>1410 </div>1411 </div>1412 )1413}1414```14151416You no longer need the `xIsNext` state declaration or the calls to `setXIsNext`. Now, there’s no1417chance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding1418the components.14191420### Wrapping up14211422Congratulations! You’ve created a tic-tac-toe game that:14231424- Lets you play tic-tac-toe,1425- Indicates when a player has won the game or when is drawn,1426- Stores a game’s history as a game progresses,1427- Allows players to review a game’s history and see previous versions of a game’s board.14281429Nice work! We hope you now feel like you have a decent grasp of how React and Zustand works.
deleted:docs/guides/updating-state.md-141 removed
1---2title: Updating state3nav: 24---56## Flat updates78Updating state with Zustand is simple! Call the provided `set` function with9the new state, and it will be shallowly merged with the existing state in the10store. **Note** See next section for nested state.1112```tsx13import { create } from 'zustand'1415type State = {16 firstName: string17 lastName: string18}1920type Action = {21 updateFirstName: (firstName: State['firstName']) => void22 updateLastName: (lastName: State['lastName']) => void23}2425// Create your store, which includes both state and (optionally) actions26const usePersonStore = create<State & Action>((set) => ({27 firstName: '',28 lastName: '',29 updateFirstName: (firstName) => set(() => ({ firstName: firstName })),30 updateLastName: (lastName) => set(() => ({ lastName: lastName })),31}))3233// In consuming app34function App() {35 // "select" the needed state and actions, in this case, the firstName value36 // and the action updateFirstName37 const firstName = usePersonStore((state) => state.firstName)38 const updateFirstName = usePersonStore((state) => state.updateFirstName)3940 return (41 <main>42 <label>43 First name44 <input45 // Update the "firstName" state46 onChange={(e) => updateFirstName(e.currentTarget.value)}47 value={firstName}48 />49 </label>5051 <p>52 Hello, <strong>{firstName}!</strong>53 </p>54 </main>55 )56}57```5859## Deeply nested object6061If you have a deep state object like this:6263```ts64type State = {65 deep: {66 nested: {67 obj: { count: number }68 }69 }70}71```7273Updating nested state requires some effort to ensure the process is completed74immutably.7576### Normal approach7778Similar to React or Redux, the normal approach is to copy each level of the79state object. This is done with the spread operator `...`, and by manually80merging that in with the new state values. Like so:8182```ts83 normalInc: () =>84 set((state) => ({85 deep: {86 ...state.deep,87 nested: {88 ...state.deep.nested,89 obj: {90 ...state.deep.nested.obj,91 count: state.deep.nested.obj.count + 192 }93 }94 }95 })),96```9798This is very long! Let's explore some alternatives that will make your life99easier.100101### With Immer102103Many people use [Immer](https://github.com/immerjs/immer) to update nested104values. Immer can be used anytime you need to update nested state such as in105React, Redux and of course, Zustand!106107You can use Immer to shorten your state updates for deeply nested object. Let's108take a look at an example:109110```ts111 immerInc: () =>112 set(produce((state: State) => { ++state.deep.nested.obj.count })),113```114115What a reduction! Please take note of the [gotchas listed here](../integrations/immer-middleware.md).116117### With optics-ts118119There is another option with [optics-ts](https://github.com/akheron/optics-ts/):120121```ts122 opticsInc: () =>123 set(O.modify(O.optic<State>().path("deep.nested.obj.count"))((c) => c + 1)),124```125126Unlike Immer, optics-ts doesn't use proxies or mutation syntax.127128### With Ramda129130You can also use [Ramda](https://ramdajs.com/):131132```ts133 ramdaInc: () =>134 set(R.modifyPath(["deep", "nested", "obj", "count"], (c) => c + 1)),135```136137Both ramda and optics-ts also work with types.138139### Demo140141https://stackblitz.com/edit/vitejs-vite-j6bjdygu
deleted:docs/hooks/use-shallow.md-266 removed
1---2title: useShallow ⚛️3description: How to memoize selector functions4nav: 285---67`useShallow` is a React Hook that lets you optimize re-renders.89```js10const memoizedSelector = useShallow(selector)11```1213- [Types](#types)14 - [Signature](#signature)15- [Reference](#reference)16- [Usage](#usage)17 - [Writing a memoized selector](#writing-a-memoized-selector)18- [Troubleshooting](#troubleshooting)1920### Signature2122```ts23useShallow<T, U = T>(selectorFn: (state: T) => U): (state: T) => U24```2526## Reference2728### `useShallow(selectorFn)`2930#### Parameters3132- `selectorFn`: A function that lets you return data that is based on current state.3334#### Returns3536`useShallow` returns a memoized version of a selector function using a shallow comparison for37memoization.3839## Usage4041### Writing a memoized selector4243First, we need to setup a store to hold the state for the bear family. In this store, we define44three properties: `papaBear`, `mamaBear`, and `babyBear`, each representing a different member of45the bear family and their respective oatmeal pot sizes.4647```tsx48import { create } from 'zustand'4950type BearFamilyMealsStore = {51 [key: string]: string52}5354const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({55 papaBear: 'large porridge-pot',56 mamaBear: 'middle-size porridge pot',57 babyBear: 'A little, small, wee pot',58}))59```6061Next, we'll create a `BearNames` component that retrieves the keys of our state (the bear family62members) and displays them.6364```tsx65function BearNames() {66 const names = useBearFamilyMealsStore((state) => Object.keys(state))6768 return <div>{names.join(', ')}</div>69}70```7172Next, we will create a `UpdateBabyBearMeal` component that periodically updates baby bear's meal73choice.7475```tsx76const meals = [77 'A tiny, little, wee bowl',78 'A small, petite, tiny pot',79 'A wee, itty-bitty, small bowl',80 'A little, petite, tiny dish',81 'A tiny, small, wee vessel',82 'A small, little, wee cauldron',83 'A little, tiny, small cup',84 'A wee, small, little jar',85 'A tiny, wee, small pan',86 'A small, wee, little crock',87]8889function UpdateBabyBearMeal() {90 useEffect(() => {91 const timer = setInterval(() => {92 useBearFamilyMealsStore.setState({93 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],94 })95 }, 1000)9697 return () => {98 clearInterval(timer)99 }100 }, [])101102 return null103}104```105106Finally, we combine both components in the `App` component to see them in action.107108```tsx109export default function App() {110 return (111 <>112 <UpdateBabyBearMeal />113 <BearNames />114 </>115 )116}117```118119Here is what the code should look like:120121```tsx122import { useEffect } from 'react'123import { create } from 'zustand'124125type BearFamilyMealsStore = {126 [key: string]: string127}128129const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({130 papaBear: 'large porridge-pot',131 mamaBear: 'middle-size porridge pot',132 babyBear: 'A little, small, wee pot',133}))134135const meals = [136 'A tiny, little, wee bowl',137 'A small, petite, tiny pot',138 'A wee, itty-bitty, small bowl',139 'A little, petite, tiny dish',140 'A tiny, small, wee vessel',141 'A small, little, wee cauldron',142 'A little, tiny, small cup',143 'A wee, small, little jar',144 'A tiny, wee, small pan',145 'A small, wee, little crock',146]147148function UpdateBabyBearMeal() {149 useEffect(() => {150 const timer = setInterval(() => {151 useBearFamilyMealsStore.setState({152 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],153 })154 }, 1000)155156 return () => {157 clearInterval(timer)158 }159 }, [])160161 return null162}163164function BearNames() {165 const names = useBearFamilyMealsStore((state) => Object.keys(state))166167 return <div>{names.join(', ')}</div>168}169170export default function App() {171 return (172 <>173 <UpdateBabyBearMeal />174 <BearNames />175 </>176 )177}178```179180Everything might look fine, but there’s a small problem: the `BearNames` component keeps181re-rendering even if the names haven’t changed. This happens because the component re-renders182whenever any part of the state changes, even if the specific part we care about (the list of names) hasn’t changed.183184To fix this, we use `useShallow` to make sure the component only re-renders when the actual keys of185the state change:186187```tsx188function BearNames() {189 const names = useBearFamilyMealsStore(190 useShallow((state) => Object.keys(state)),191 )192193 return <div>{names.join(', ')}</div>194}195```196197Here is what the code should look like:198199```tsx200import { useEffect } from 'react'201import { create } from 'zustand'202import { useShallow } from 'zustand/react/shallow'203204type BearFamilyMealsStore = {205 [key: string]: string206}207208const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({209 papaBear: 'large porridge-pot',210 mamaBear: 'middle-size porridge pot',211 babyBear: 'A little, small, wee pot',212}))213214const meals = [215 'A tiny, little, wee bowl',216 'A small, petite, tiny pot',217 'A wee, itty-bitty, small bowl',218 'A little, petite, tiny dish',219 'A tiny, small, wee vessel',220 'A small, little, wee cauldron',221 'A little, tiny, small cup',222 'A wee, small, little jar',223 'A tiny, wee, small pan',224 'A small, wee, little crock',225]226227function UpdateBabyBearMeal() {228 useEffect(() => {229 const timer = setInterval(() => {230 useBearFamilyMealsStore.setState({231 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],232 })233 }, 1000)234235 return () => {236 clearInterval(timer)237 }238 }, [])239240 return null241}242243function BearNames() {244 const names = useBearFamilyMealsStore(245 useShallow((state) => Object.keys(state)),246 )247248 return <div>{names.join(', ')}</div>249}250251export default function App() {252 return (253 <>254 <UpdateBabyBearMeal />255 <BearNames />256 </>257 )258}259```260261By using `useShallow`, we optimized the rendering process, ensuring that the component only262re-renders when necessary, which improves overall performance.263264## Troubleshooting265266TBD
deleted:docs/hooks/use-store-with-equality-fn.md-956 removed
1---2title: useStoreWithEqualityFn ⚛️3description: How to use vanilla stores effectively in React4nav: 295---67`useStoreWithEqualityFn` is a React Hook that lets you use a vanilla store in React, just like8`useStore`. However, it offers a way to define a custom equality check. This allows for more9granular control over when components re-render, improving performance and responsiveness.1011> [!IMPORTANT]12> In order to use `useStoreWithEqualityFn` from `zustand/traditional` you need to install13> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.1415```js16const someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)17```1819- [Types](#types)20 - [Signature](#signature)21- [Reference](#reference)22- [Usage](#usage)23 - [Using a global vanilla store in React](#using-a-global-vanilla-store-in-react)24 - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)25 - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)26 - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)27- [Troubleshooting](#troubleshooting)2829### Signature3031```ts32useStoreWithEqualityFn<T, U = T>(store: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U33```3435## Reference3637### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`3839#### Parameters4041- `storeApi`: The instance that lets you access to store API utilities.42- `selectorFn`: A function that lets you return data that is based on current state.43- `equalityFn`: A function that lets you skip re-renders.4445#### Returns4647`useStoreWithEqualityFn` returns any data based on current state depending on the selector function,48and lets you skip re-renders using an equality function. It should take a store, a selector49function, and an equality function as arguments.5051## Usage5253### Using a global vanilla store in React5455First, let's set up a store that will hold the position of the dot on the screen. We'll define the56store to manage `x` and `y` coordinates and provide an action to update these coordinates.5758```tsx59import { createStore, useStore } from 'zustand'6061type PositionStoreState = { position: { x: number; y: number } }6263type PositionStoreActions = {64 setPosition: (nextPosition: PositionStoreState['position']) => void65}6667type PositionStore = PositionStoreState & PositionStoreActions6869const positionStore = createStore<PositionStore>()((set) => ({70 position: { x: 0, y: 0 },71 setPosition: (position) => set({ position }),72}))73```7475Next, we'll create a `MovingDot` component that renders a div representing the dot. This component76will use the store to track and update the dot's position.7778```tsx79function MovingDot() {80 const position = useStoreWithEqualityFn(81 positionStore,82 (state) => state.position,83 shallow,84 )85 const setPosition = useStoreWithEqualityFn(86 positionStore,87 (state) => state.setPosition,88 shallow,89 )9091 return (92 <div93 onPointerMove={(e) => {94 setPosition({95 x: e.clientX,96 y: e.clientY,97 })98 }}99 style={{100 position: 'relative',101 width: '100vw',102 height: '100vh',103 }}104 >105 <div106 style={{107 position: 'absolute',108 backgroundColor: 'red',109 borderRadius: '50%',110 transform: `translate(${position.x}px, ${position.y}px)`,111 left: -10,112 top: -10,113 width: 20,114 height: 20,115 }}116 />117 </div>118 )119}120```121122Finally, we’ll render the `MovingDot` component in our `App` component.123124```tsx125export default function App() {126 return <MovingDot />127}128```129130Here is what the code should look like:131132```tsx133import { createStore } from 'zustand'134import { useStoreWithEqualityFn } from 'zustand/traditional'135import { shallow } from 'zustand/shallow'136137type PositionStoreState = { position: { x: number; y: number } }138139type PositionStoreActions = {140 setPosition: (nextPosition: PositionStoreState['position']) => void141}142143type PositionStore = PositionStoreState & PositionStoreActions144145const positionStore = createStore<PositionStore>()((set) => ({146 position: { x: 0, y: 0 },147 setPosition: (position) => set({ position }),148}))149150function MovingDot() {151 const position = useStoreWithEqualityFn(152 positionStore,153 (state) => state.position,154 shallow,155 )156 const setPosition = useStoreWithEqualityFn(157 positionStore,158 (state) => state.setPosition,159 shallow,160 )161162 return (163 <div164 onPointerMove={(e) => {165 setPosition({166 x: e.clientX,167 y: e.clientY,168 })169 }}170 style={{171 position: 'relative',172 width: '100vw',173 height: '100vh',174 }}175 >176 <div177 style={{178 position: 'absolute',179 backgroundColor: 'red',180 borderRadius: '50%',181 transform: `translate(${position.x}px, ${position.y}px)`,182 left: -10,183 top: -10,184 width: 20,185 height: 20,186 }}187 />188 </div>189 )190}191192export default function App() {193 return <MovingDot />194}195```196197### Using dynamic global vanilla stores in React198199First, we'll create a factory function that generates a store for managing the counter state.200Each tab will have its own instance of this store.201202```ts203import { createStore } from 'zustand'204205type CounterState = {206 count: number207}208209type CounterActions = { increment: () => void }210211type CounterStore = CounterState & CounterActions212213const createCounterStore = () => {214 return createStore<CounterStore>()((set) => ({215 count: 0,216 increment: () => {217 set((state) => ({ count: state.count + 1 }))218 },219 }))220}221```222223Next, we'll create a factory function that manages the creation and retrieval of counter stores.224This allows each tab to have its own independent counter.225226```ts227const defaultCounterStores = new Map<228 string,229 ReturnType<typeof createCounterStore>230>()231232const createCounterStoreFactory = (233 counterStores: typeof defaultCounterStores,234) => {235 return (counterStoreKey: string) => {236 if (!counterStores.has(counterStoreKey)) {237 counterStores.set(counterStoreKey, createCounterStore())238 }239 return counterStores.get(counterStoreKey)!240 }241}242243const getOrCreateCounterStoreByKey =244 createCounterStoreFactory(defaultCounterStores)245```246247Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s248counter.249250```tsx251const [currentTabIndex, setCurrentTabIndex] = useState(0)252const counterState = useStoreWithEqualityFn(253 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),254 (state) => state,255 shallow,256)257258return (259 <div style={{ fontFamily: 'monospace' }}>260 <div261 style={{262 display: 'flex',263 gap: '0.5rem',264 borderBottom: '1px solid salmon',265 paddingBottom: 4,266 }}267 >268 <button269 type="button"270 style={{271 border: '1px solid salmon',272 backgroundColor: '#fff',273 cursor: 'pointer',274 }}275 onClick={() => setCurrentTabIndex(0)}276 >277 Tab 1278 </button>279 <button280 type="button"281 style={{282 border: '1px solid salmon',283 backgroundColor: '#fff',284 cursor: 'pointer',285 }}286 onClick={() => setCurrentTabIndex(1)}287 >288 Tab 2289 </button>290 <button291 type="button"292 style={{293 border: '1px solid salmon',294 backgroundColor: '#fff',295 cursor: 'pointer',296 }}297 onClick={() => setCurrentTabIndex(2)}298 >299 Tab 3300 </button>301 </div>302 <div style={{ padding: 4 }}>303 Content of Tab {currentTabIndex + 1}304 <br /> <br />305 <button type="button" onClick={() => counterState.increment()}>306 Count: {counterState.count}307 </button>308 </div>309 </div>310)311```312313Finally, we'll create the `App` component, which renders the tabs and their respective counters.314The counter state is managed independently for each tab.315316```tsx317export default function App() {318 return <Tabs />319}320```321322Here is what the code should look like:323324```tsx325import { useState } from 'react'326import { createStore } from 'zustand'327import { useStoreWithEqualityFn } from 'zustand/traditional'328import { shallow } from 'zustand/shallow'329330type CounterState = {331 count: number332}333334type CounterActions = { increment: () => void }335336type CounterStore = CounterState & CounterActions337338const createCounterStore = () => {339 return createStore<CounterStore>()((set) => ({340 count: 0,341 increment: () => {342 set((state) => ({ count: state.count + 1 }))343 },344 }))345}346347const defaultCounterStores = new Map<348 string,349 ReturnType<typeof createCounterStore>350>()351352const createCounterStoreFactory = (353 counterStores: typeof defaultCounterStores,354) => {355 return (counterStoreKey: string) => {356 if (!counterStores.has(counterStoreKey)) {357 counterStores.set(counterStoreKey, createCounterStore())358 }359 return counterStores.get(counterStoreKey)!360 }361}362363const getOrCreateCounterStoreByKey =364 createCounterStoreFactory(defaultCounterStores)365366export default function App() {367 const [currentTabIndex, setCurrentTabIndex] = useState(0)368 const counterState = useStoreWithEqualityFn(369 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),370 (state) => state,371 shallow,372 )373374 return (375 <div style={{ fontFamily: 'monospace' }}>376 <div377 style={{378 display: 'flex',379 gap: '0.5rem',380 borderBottom: '1px solid salmon',381 paddingBottom: 4,382 }}383 >384 <button385 type="button"386 style={{387 border: '1px solid salmon',388 backgroundColor: '#fff',389 cursor: 'pointer',390 }}391 onClick={() => setCurrentTabIndex(0)}392 >393 Tab 1394 </button>395 <button396 type="button"397 style={{398 border: '1px solid salmon',399 backgroundColor: '#fff',400 cursor: 'pointer',401 }}402 onClick={() => setCurrentTabIndex(1)}403 >404 Tab 2405 </button>406 <button407 type="button"408 style={{409 border: '1px solid salmon',410 backgroundColor: '#fff',411 cursor: 'pointer',412 }}413 onClick={() => setCurrentTabIndex(2)}414 >415 Tab 3416 </button>417 </div>418 <div style={{ padding: 4 }}>419 Content of Tab {currentTabIndex + 1}420 <br /> <br />421 <button type="button" onClick={() => counterState.increment()}>422 Count: {counterState.count}423 </button>424 </div>425 </div>426 )427}428```429430### Using scoped (non-global) vanilla store in React431432First, let's set up a store that will hold the position of the dot on the screen. We'll define the433store to manage `x` and `y` coordinates and provide an action to update these coordinates.434435```tsx436type PositionStoreState = { position: { x: number; y: number } }437438type PositionStoreActions = {439 setPosition: (nextPosition: PositionStoreState['position']) => void440}441442type PositionStore = PositionStoreState & PositionStoreActions443444const createPositionStore = () => {445 return createStore<PositionStore>()((set) => ({446 position: { x: 0, y: 0 },447 setPosition: (position) => set({ position }),448 }))449}450```451452Next, we'll create a context and a provider component to pass down the store through the React453component tree. This allows each `MovingDot` component to have its own independent state.454455```tsx456const PositionStoreContext = createContext<ReturnType<457 typeof createPositionStore458> | null>(null)459460function PositionStoreProvider({ children }: { children: ReactNode }) {461 const [store] = useState(() => createPositionStore())462 return (463 <PositionStoreContext.Provider value={store}>464 {children}465 </PositionStoreContext.Provider>466 )467}468```469470To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook471will read the store from the context and allow us to select specific parts of the state.472473```ts474function usePositionStore<U>(selector: (state: PositionStore) => U) {475 const store = useContext(PositionStoreContext)476477 if (store === null) {478 throw new Error(479 'usePositionStore must be used within PositionStoreProvider',480 )481 }482483 return useStoreWithEqualityFn(store, selector, shallow)484}485```486487Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor488within its container.489490```tsx491function MovingDot({ color }: { color: string }) {492 const position = usePositionStore((state) => state.position)493 const setPosition = usePositionStore((state) => state.setPosition)494495 return (496 <div497 onPointerMove={(e) => {498 setPosition({499 x:500 e.clientX > e.currentTarget.clientWidth501 ? e.clientX - e.currentTarget.clientWidth502 : e.clientX,503 y: e.clientY,504 })505 }}506 style={{507 position: 'relative',508 width: '50vw',509 height: '100vh',510 }}511 >512 <div513 style={{514 position: 'absolute',515 backgroundColor: color,516 borderRadius: '50%',517 transform: `translate(${position.x}px, ${position.y}px)`,518 left: -10,519 top: -10,520 width: 20,521 height: 20,522 }}523 />524 </div>525 )526}527```528529Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`530components, each with its own independent state.531532```tsx533export default function App() {534 return (535 <div style={{ display: 'flex' }}>536 <PositionStoreProvider>537 <MovingDot color="red" />538 </PositionStoreProvider>539 <PositionStoreProvider>540 <MovingDot color="blue" />541 </PositionStoreProvider>542 </div>543 )544}545```546547Here is what the code should look like:548549```tsx550import { type ReactNode, useState, createContext, useContext } from 'react'551import { createStore } from 'zustand'552import { useStoreWithEqualityFn } from 'zustand/traditional'553import { shallow } from 'zustand/shallow'554555type PositionStoreState = { position: { x: number; y: number } }556557type PositionStoreActions = {558 setPosition: (nextPosition: PositionStoreState['position']) => void559}560561type PositionStore = PositionStoreState & PositionStoreActions562563const createPositionStore = () => {564 return createStore<PositionStore>()((set) => ({565 position: { x: 0, y: 0 },566 setPosition: (position) => set({ position }),567 }))568}569570const PositionStoreContext = createContext<ReturnType<571 typeof createPositionStore572> | null>(null)573574function PositionStoreProvider({ children }: { children: ReactNode }) {575 const [store] = useState(() => createPositionStore())576 return (577 <PositionStoreContext.Provider value={store}>578 {children}579 </PositionStoreContext.Provider>580 )581}582583function usePositionStore<U>(selector: (state: PositionStore) => U) {584 const store = useContext(PositionStoreContext)585586 if (store === null) {587 throw new Error(588 'usePositionStore must be used within PositionStoreProvider',589 )590 }591592 return useStoreWithEqualityFn(store, selector, shallow)593}594595function MovingDot({ color }: { color: string }) {596 const position = usePositionStore((state) => state.position)597 const setPosition = usePositionStore((state) => state.setPosition)598599 return (600 <div601 onPointerMove={(e) => {602 setPosition({603 x:604 e.clientX > e.currentTarget.clientWidth605 ? e.clientX - e.currentTarget.clientWidth606 : e.clientX,607 y: e.clientY,608 })609 }}610 style={{611 position: 'relative',612 width: '50vw',613 height: '100vh',614 }}615 >616 <div617 style={{618 position: 'absolute',619 backgroundColor: color,620 borderRadius: '50%',621 transform: `translate(${position.x}px, ${position.y}px)`,622 left: -10,623 top: -10,624 width: 20,625 height: 20,626 }}627 />628 </div>629 )630}631632export default function App() {633 return (634 <div style={{ display: 'flex' }}>635 <PositionStoreProvider>636 <MovingDot color="red" />637 </PositionStoreProvider>638 <PositionStoreProvider>639 <MovingDot color="blue" />640 </PositionStoreProvider>641 </div>642 )643}644```645646### Using dynamic scoped (non-global) vanilla stores in React647648First, we'll create a factory function that generates a store for managing the counter state.649Each tab will have its own instance of this store.650651```ts652type CounterState = {653 count: number654}655656type CounterActions = { increment: () => void }657658type CounterStore = CounterState & CounterActions659660const createCounterStore = () => {661 return createStore<CounterStore>()((set) => ({662 count: 0,663 increment: () => {664 set((state) => ({ count: state.count + 1 }))665 },666 }))667}668```669670Next, we'll create a factory function that manages the creation and retrieval of counter stores.671This allows each tab to have its own independent counter.672673```ts674const createCounterStoreFactory = (675 counterStores: Map<string, ReturnType<typeof createCounterStore>>,676) => {677 return (counterStoreKey: string) => {678 if (!counterStores.has(counterStoreKey)) {679 counterStores.set(counterStoreKey, createCounterStore())680 }681 return counterStores.get(counterStoreKey)!682 }683}684```685686Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context687for this.688689```tsx690const CounterStoresContext = createContext(null)691692const CounterStoresProvider = ({ children }) => {693 const [stores] = useState(694 () => new Map<string, ReturnType<typeof createCounterStore>>(),695 )696697 return (698 <CounterStoresContext.Provider value={stores}>699 {children}700 </CounterStoresContext.Provider>701 )702}703```704705Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a706given tab.707708```tsx709const useCounterStore = <U,>(710 key: string,711 selector: (state: CounterStore) => U,712) => {713 const stores = useContext(CounterStoresContext)714715 if (stores === undefined) {716 throw new Error('useCounterStore must be used within CounterStoresProvider')717 }718719 const getOrCreateCounterStoreByKey = useCallback(720 (key: string) => createCounterStoreFactory(stores!)(key),721 [stores],722 )723724 return useStore(getOrCreateCounterStoreByKey(key), selector)725}726```727728Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s729counter.730731```tsx732function Tabs() {733 const [currentTabIndex, setCurrentTabIndex] = useState(0)734 const counterState = useCounterStore(735 `tab-${currentTabIndex}`,736 (state) => state,737 )738739 return (740 <div style={{ fontFamily: 'monospace' }}>741 <div742 style={{743 display: 'flex',744 gap: '0.5rem',745 borderBottom: '1px solid salmon',746 paddingBottom: 4,747 }}748 >749 <button750 type="button"751 style={{752 border: '1px solid salmon',753 backgroundColor: '#fff',754 cursor: 'pointer',755 }}756 onClick={() => setCurrentTabIndex(0)}757 >758 Tab 1759 </button>760 <button761 type="button"762 style={{763 border: '1px solid salmon',764 backgroundColor: '#fff',765 cursor: 'pointer',766 }}767 onClick={() => setCurrentTabIndex(1)}768 >769 Tab 2770 </button>771 <button772 type="button"773 style={{774 border: '1px solid salmon',775 backgroundColor: '#fff',776 cursor: 'pointer',777 }}778 onClick={() => setCurrentTabIndex(2)}779 >780 Tab 3781 </button>782 </div>783 <div style={{ padding: 4 }}>784 Content of Tab {currentTabIndex + 1}785 <br /> <br />786 <button type="button" onClick={() => counterState.increment()}>787 Count: {counterState.count}788 </button>789 </div>790 </div>791 )792}793```794795Finally, we'll create the `App` component, which renders the tabs and their respective counters.796The counter state is managed independently for each tab.797798```tsx799export default function App() {800 return (801 <CounterStoresProvider>802 <Tabs />803 </CounterStoresProvider>804 )805}806```807808Here is what the code should look like:809810```tsx811import {812 type ReactNode,813 useState,814 useCallback,815 useContext,816 createContext,817} from 'react'818import { createStore, useStore } from 'zustand'819820type CounterState = {821 count: number822}823824type CounterActions = { increment: () => void }825826type CounterStore = CounterState & CounterActions827828const createCounterStore = () => {829 return createStore<CounterStore>()((set) => ({830 count: 0,831 increment: () => {832 set((state) => ({ count: state.count + 1 }))833 },834 }))835}836837const createCounterStoreFactory = (838 counterStores: Map<string, ReturnType<typeof createCounterStore>>,839) => {840 return (counterStoreKey: string) => {841 if (!counterStores.has(counterStoreKey)) {842 counterStores.set(counterStoreKey, createCounterStore())843 }844 return counterStores.get(counterStoreKey)!845 }846}847848const CounterStoresContext = createContext<Map<849 string,850 ReturnType<typeof createCounterStore>851> | null>(null)852853const CounterStoresProvider = ({ children }: { children: ReactNode }) => {854 const [stores] = useState(855 () => new Map<string, ReturnType<typeof createCounterStore>>(),856 )857858 return (859 <CounterStoresContext.Provider value={stores}>860 {children}861 </CounterStoresContext.Provider>862 )863}864865const useCounterStore = <U,>(866 key: string,867 selector: (state: CounterStore) => U,868) => {869 const stores = useContext(CounterStoresContext)870871 if (stores === undefined) {872 throw new Error('useCounterStore must be used within CounterStoresProvider')873 }874875 const getOrCreateCounterStoreByKey = useCallback(876 (key: string) => createCounterStoreFactory(stores!)(key),877 [stores],878 )879880 return useStore(getOrCreateCounterStoreByKey(key), selector)881}882883function Tabs() {884 const [currentTabIndex, setCurrentTabIndex] = useState(0)885 const counterState = useCounterStore(886 `tab-${currentTabIndex}`,887 (state) => state,888 )889890 return (891 <div style={{ fontFamily: 'monospace' }}>892 <div893 style={{894 display: 'flex',895 gap: '0.5rem',896 borderBottom: '1px solid salmon',897 paddingBottom: 4,898 }}899 >900 <button901 type="button"902 style={{903 border: '1px solid salmon',904 backgroundColor: '#fff',905 cursor: 'pointer',906 }}907 onClick={() => setCurrentTabIndex(0)}908 >909 Tab 1910 </button>911 <button912 type="button"913 style={{914 border: '1px solid salmon',915 backgroundColor: '#fff',916 cursor: 'pointer',917 }}918 onClick={() => setCurrentTabIndex(1)}919 >920 Tab 2921 </button>922 <button923 type="button"924 style={{925 border: '1px solid salmon',926 backgroundColor: '#fff',927 cursor: 'pointer',928 }}929 onClick={() => setCurrentTabIndex(2)}930 >931 Tab 3932 </button>933 </div>934 <div style={{ padding: 4 }}>935 Content of Tab {currentTabIndex + 1}936 <br /> <br />937 <button type="button" onClick={() => counterState.increment()}>938 Count: {counterState.count}939 </button>940 </div>941 </div>942 )943}944945export default function App() {946 return (947 <CounterStoresProvider>948 <Tabs />949 </CounterStoresProvider>950 )951}952```953954## Troubleshooting955956TBD
deleted:docs/hooks/use-store.md-922 removed
1---2title: useStore ⚛️3description: How to use vanilla stores in React4nav: 305---67`useStore` is a React Hook that lets you use a vanilla store in React.89```js10const someState = useStore(store, selectorFn)11```1213- [Types](#types)14 - [Signature](#signature)15- [Reference](#reference)16- [Usage](#usage)17 - [Use a vanilla store in React](#use-a-vanilla-store-in-react)18 - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)19 - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)20 - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)21- [Troubleshooting](#troubleshooting)2223## Types2425### Signature2627```ts28useStore<StoreApi<T>, U = T>(store: StoreApi<T>, selectorFn?: (state: T) => U) => UseBoundStore<StoreApi<T>>29```3031## Reference3233### `useStore(store, selectorFn)`3435#### Parameters3637- `storeApi`: The instance that lets you access to store API utilities.38- `selectorFn`: A function that lets you return data that is based on current state.3940#### Returns4142`useStore` returns any data based on current state depending on the selector function. It should43take a store, and a selector function as arguments.4445## Usage4647### Using a global vanilla store in React4849First, let's set up a store that will hold the position of the dot on the screen. We'll define the50store to manage `x` and `y` coordinates and provide an action to update these coordinates.5152```tsx53type PositionStoreState = { position: { x: number; y: number } }5455type PositionStoreActions = {56 setPosition: (nextPosition: PositionStoreState['position']) => void57}5859type PositionStore = PositionStoreState & PositionStoreActions6061const positionStore = createStore<PositionStore>()((set) => ({62 position: { x: 0, y: 0 },63 setPosition: (position) => set({ position }),64}))65```6667Next, we'll create a `MovingDot` component that renders a div representing the dot. This component68will use the store to track and update the dot's position.6970```tsx71function MovingDot() {72 const position = useStore(positionStore, (state) => state.position)73 const setPosition = useStore(positionStore, (state) => state.setPosition)7475 return (76 <div77 onPointerMove={(e) => {78 setPosition({79 x: e.clientX,80 y: e.clientY,81 })82 }}83 style={{84 position: 'relative',85 width: '100vw',86 height: '100vh',87 }}88 >89 <div90 style={{91 position: 'absolute',92 backgroundColor: 'red',93 borderRadius: '50%',94 transform: `translate(${position.x}px, ${position.y}px)`,95 left: -10,96 top: -10,97 width: 20,98 height: 20,99 }}100 />101 </div>102 )103}104```105106Finally, we’ll render the `MovingDot` component in our `App` component.107108```tsx109export default function App() {110 return <MovingDot />111}112```113114Here is what the code should look like:115116```tsx117import { createStore, useStore } from 'zustand'118119type PositionStoreState = { position: { x: number; y: number } }120121type PositionStoreActions = {122 setPosition: (nextPosition: PositionStoreState['position']) => void123}124125type PositionStore = PositionStoreState & PositionStoreActions126127const positionStore = createStore<PositionStore>()((set) => ({128 position: { x: 0, y: 0 },129 setPosition: (position) => set({ position }),130}))131132function MovingDot() {133 const position = useStore(positionStore, (state) => state.position)134 const setPosition = useStore(positionStore, (state) => state.setPosition)135136 return (137 <div138 onPointerMove={(e) => {139 setPosition({140 x: e.clientX,141 y: e.clientY,142 })143 }}144 style={{145 position: 'relative',146 width: '100vw',147 height: '100vh',148 }}149 >150 <div151 style={{152 position: 'absolute',153 backgroundColor: 'red',154 borderRadius: '50%',155 transform: `translate(${position.x}px, ${position.y}px)`,156 left: -10,157 top: -10,158 width: 20,159 height: 20,160 }}161 />162 </div>163 )164}165166export default function App() {167 return <MovingDot />168}169```170171### Using dynamic global vanilla stores in React172173First, we'll create a factory function that generates a store for managing the counter state.174Each tab will have its own instance of this store.175176```ts177type CounterState = {178 count: number179}180181type CounterActions = { increment: () => void }182183type CounterStore = CounterState & CounterActions184185const createCounterStore = () => {186 return createStore<CounterStore>()((set) => ({187 count: 0,188 increment: () => {189 set((state) => ({ count: state.count + 1 }))190 },191 }))192}193```194195Next, we'll create a factory function that manages the creation and retrieval of counter stores.196This allows each tab to have its own independent counter.197198```ts199const defaultCounterStores = new Map<200 string,201 ReturnType<typeof createCounterStore>202>()203204const createCounterStoreFactory = (205 counterStores: typeof defaultCounterStores,206) => {207 return (counterStoreKey: string) => {208 if (!counterStores.has(counterStoreKey)) {209 counterStores.set(counterStoreKey, createCounterStore())210 }211 return counterStores.get(counterStoreKey)!212 }213}214215const getOrCreateCounterStoreByKey =216 createCounterStoreFactory(defaultCounterStores)217```218219Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s220counter.221222```tsx223const [currentTabIndex, setCurrentTabIndex] = useState(0)224const counterState = useStore(225 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),226)227228return (229 <div style={{ fontFamily: 'monospace' }}>230 <div231 style={{232 display: 'flex',233 gap: '0.5rem',234 borderBottom: '1px solid salmon',235 paddingBottom: 4,236 }}237 >238 <button239 type="button"240 style={{241 border: '1px solid salmon',242 backgroundColor: '#fff',243 cursor: 'pointer',244 }}245 onClick={() => setCurrentTabIndex(0)}246 >247 Tab 1248 </button>249 <button250 type="button"251 style={{252 border: '1px solid salmon',253 backgroundColor: '#fff',254 cursor: 'pointer',255 }}256 onClick={() => setCurrentTabIndex(1)}257 >258 Tab 2259 </button>260 <button261 type="button"262 style={{263 border: '1px solid salmon',264 backgroundColor: '#fff',265 cursor: 'pointer',266 }}267 onClick={() => setCurrentTabIndex(2)}268 >269 Tab 3270 </button>271 </div>272 <div style={{ padding: 4 }}>273 Content of Tab {currentTabIndex + 1}274 <br /> <br />275 <button type="button" onClick={() => counterState.increment()}>276 Count: {counterState.count}277 </button>278 </div>279 </div>280)281```282283Finally, we'll create the `App` component, which renders the tabs and their respective counters.284The counter state is managed independently for each tab.285286```tsx287export default function App() {288 return <Tabs />289}290```291292Here is what the code should look like:293294```tsx295import { useState } from 'react'296import { createStore, useStore } from 'zustand'297298type CounterState = {299 count: number300}301302type CounterActions = { increment: () => void }303304type CounterStore = CounterState & CounterActions305306const createCounterStore = () => {307 return createStore<CounterStore>()((set) => ({308 count: 0,309 increment: () => {310 set((state) => ({ count: state.count + 1 }))311 },312 }))313}314315const defaultCounterStores = new Map<316 string,317 ReturnType<typeof createCounterStore>318>()319320const createCounterStoreFactory = (321 counterStores: typeof defaultCounterStores,322) => {323 return (counterStoreKey: string) => {324 if (!counterStores.has(counterStoreKey)) {325 counterStores.set(counterStoreKey, createCounterStore())326 }327 return counterStores.get(counterStoreKey)!328 }329}330331const getOrCreateCounterStoreByKey =332 createCounterStoreFactory(defaultCounterStores)333334export default function App() {335 const [currentTabIndex, setCurrentTabIndex] = useState(0)336 const counterState = useStore(337 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),338 )339340 return (341 <div style={{ fontFamily: 'monospace' }}>342 <div343 style={{344 display: 'flex',345 gap: '0.5rem',346 borderBottom: '1px solid salmon',347 paddingBottom: 4,348 }}349 >350 <button351 type="button"352 style={{353 border: '1px solid salmon',354 backgroundColor: '#fff',355 cursor: 'pointer',356 }}357 onClick={() => setCurrentTabIndex(0)}358 >359 Tab 1360 </button>361 <button362 type="button"363 style={{364 border: '1px solid salmon',365 backgroundColor: '#fff',366 cursor: 'pointer',367 }}368 onClick={() => setCurrentTabIndex(1)}369 >370 Tab 2371 </button>372 <button373 type="button"374 style={{375 border: '1px solid salmon',376 backgroundColor: '#fff',377 cursor: 'pointer',378 }}379 onClick={() => setCurrentTabIndex(2)}380 >381 Tab 3382 </button>383 </div>384 <div style={{ padding: 4 }}>385 Content of Tab {currentTabIndex + 1}386 <br /> <br />387 <button type="button" onClick={() => counterState.increment()}>388 Count: {counterState.count}389 </button>390 </div>391 </div>392 )393}394```395396### Using scoped (non-global) vanilla store in React397398First, let's set up a store that will hold the position of the dot on the screen. We'll define the399store to manage `x` and `y` coordinates and provide an action to update these coordinates.400401```tsx402type PositionStoreState = { position: { x: number; y: number } }403404type PositionStoreActions = {405 setPosition: (nextPosition: PositionStoreState['position']) => void406}407408type PositionStore = PositionStoreState & PositionStoreActions409410const createPositionStore = () => {411 return createStore<PositionStore>()((set) => ({412 position: { x: 0, y: 0 },413 setPosition: (position) => set({ position }),414 }))415}416```417418Next, we'll create a context and a provider component to pass down the store through the React419component tree. This allows each `MovingDot` component to have its own independent state.420421```tsx422const PositionStoreContext = createContext<ReturnType<423 typeof createPositionStore424> | null>(null)425426function PositionStoreProvider({ children }: { children: ReactNode }) {427 const [store] = useState(() => createPositionStore())428 return (429 <PositionStoreContext.Provider value={store}>430 {children}431 </PositionStoreContext.Provider>432 )433}434```435436To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook437will read the store from the context and allow us to select specific parts of the state.438439```ts440function usePositionStore<U>(selector: (state: PositionStore) => U) {441 const store = useContext(PositionStoreContext)442443 if (store === null) {444 throw new Error(445 'usePositionStore must be used within PositionStoreProvider',446 )447 }448449 return useStore(store, selector)450}451```452453Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor454within its container.455456```tsx457function MovingDot({ color }: { color: string }) {458 const position = usePositionStore((state) => state.position)459 const setPosition = usePositionStore((state) => state.setPosition)460461 return (462 <div463 onPointerMove={(e) => {464 setPosition({465 x:466 e.clientX > e.currentTarget.clientWidth467 ? e.clientX - e.currentTarget.clientWidth468 : e.clientX,469 y: e.clientY,470 })471 }}472 style={{473 position: 'relative',474 width: '50vw',475 height: '100vh',476 }}477 >478 <div479 style={{480 position: 'absolute',481 backgroundColor: color,482 borderRadius: '50%',483 transform: `translate(${position.x}px, ${position.y}px)`,484 left: -10,485 top: -10,486 width: 20,487 height: 20,488 }}489 />490 </div>491 )492}493```494495Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`496components, each with its own independent state.497498```tsx499export default function App() {500 return (501 <div style={{ display: 'flex' }}>502 <PositionStoreProvider>503 <MovingDot color="red" />504 </PositionStoreProvider>505 <PositionStoreProvider>506 <MovingDot color="blue" />507 </PositionStoreProvider>508 </div>509 )510}511```512513Here is what the code should look like:514515```tsx516import { type ReactNode, useState, createContext, useContext } from 'react'517import { createStore, useStore } from 'zustand'518519type PositionStoreState = { position: { x: number; y: number } }520521type PositionStoreActions = {522 setPosition: (nextPosition: PositionStoreState['position']) => void523}524525type PositionStore = PositionStoreState & PositionStoreActions526527const createPositionStore = () => {528 return createStore<PositionStore>()((set) => ({529 position: { x: 0, y: 0 },530 setPosition: (position) => set({ position }),531 }))532}533534const PositionStoreContext = createContext<ReturnType<535 typeof createPositionStore536> | null>(null)537538function PositionStoreProvider({ children }: { children: ReactNode }) {539 const [store] = useState(() => createPositionStore())540 return (541 <PositionStoreContext.Provider value={store}>542 {children}543 </PositionStoreContext.Provider>544 )545}546547function usePositionStore<U>(selector: (state: PositionStore) => U) {548 const store = useContext(PositionStoreContext)549550 if (store === null) {551 throw new Error(552 'usePositionStore must be used within PositionStoreProvider',553 )554 }555556 return useStore(store, selector)557}558559function MovingDot({ color }: { color: string }) {560 const position = usePositionStore((state) => state.position)561 const setPosition = usePositionStore((state) => state.setPosition)562563 return (564 <div565 onPointerMove={(e) => {566 setPosition({567 x:568 e.clientX > e.currentTarget.clientWidth569 ? e.clientX - e.currentTarget.clientWidth570 : e.clientX,571 y: e.clientY,572 })573 }}574 style={{575 position: 'relative',576 width: '50vw',577 height: '100vh',578 }}579 >580 <div581 style={{582 position: 'absolute',583 backgroundColor: color,584 borderRadius: '50%',585 transform: `translate(${position.x}px, ${position.y}px)`,586 left: -10,587 top: -10,588 width: 20,589 height: 20,590 }}591 />592 </div>593 )594}595596export default function App() {597 return (598 <div style={{ display: 'flex' }}>599 <PositionStoreProvider>600 <MovingDot color="red" />601 </PositionStoreProvider>602 <PositionStoreProvider>603 <MovingDot color="blue" />604 </PositionStoreProvider>605 </div>606 )607}608```609610### Using dynamic scoped (non-global) vanilla stores in React611612First, we'll create a factory function that generates a store for managing the counter state.613Each tab will have its own instance of this store.614615```ts616import { createStore } from 'zustand'617618type CounterState = {619 count: number620}621622type CounterActions = { increment: () => void }623624type CounterStore = CounterState & CounterActions625626const createCounterStore = () => {627 return createStore<CounterStore>()((set) => ({628 count: 0,629 increment: () => {630 set((state) => ({ count: state.count + 1 }))631 },632 }))633}634```635636Next, we'll create a factory function that manages the creation and retrieval of counter stores.637This allows each tab to have its own independent counter.638639```ts640const createCounterStoreFactory = (641 counterStores: Map<string, ReturnType<typeof createCounterStore>>,642) => {643 return (counterStoreKey: string) => {644 if (!counterStores.has(counterStoreKey)) {645 counterStores.set(counterStoreKey, createCounterStore())646 }647 return counterStores.get(counterStoreKey)!648 }649}650```651652Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context653for this.654655```tsx656const CounterStoresContext = createContext(null)657658const CounterStoresProvider = ({ children }) => {659 const [stores] = useState(660 () => new Map<string, ReturnType<typeof createCounterStore>>(),661 )662663 return (664 <CounterStoresContext.Provider value={stores}>665 {children}666 </CounterStoresContext.Provider>667 )668}669```670671Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a672given tab.673674```tsx675const useCounterStore = <U>(676 currentTabIndex: number,677 selector: (state: CounterStore) => U,678) => {679 const stores = useContext(CounterStoresContext)680681 if (stores === undefined) {682 throw new Error('useCounterStore must be used within CounterStoresProvider')683 }684685 const getOrCreateCounterStoreByKey = useCallback(686 () => createCounterStoreFactory(stores),687 [stores],688 )689690 return useStore(getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`))691}692```693694Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s695counter.696697```tsx698function Tabs() {699 const [currentTabIndex, setCurrentTabIndex] = useState(0)700 const counterState = useCounterStore(701 `tab-${currentTabIndex}`,702 (state) => state,703 )704705 return (706 <div style={{ fontFamily: 'monospace' }}>707 <div708 style={{709 display: 'flex',710 gap: '0.5rem',711 borderBottom: '1px solid salmon',712 paddingBottom: 4,713 }}714 >715 <button716 type="button"717 style={{718 border: '1px solid salmon',719 backgroundColor: '#fff',720 cursor: 'pointer',721 }}722 onClick={() => setCurrentTabIndex(0)}723 >724 Tab 1725 </button>726 <button727 type="button"728 style={{729 border: '1px solid salmon',730 backgroundColor: '#fff',731 cursor: 'pointer',732 }}733 onClick={() => setCurrentTabIndex(1)}734 >735 Tab 2736 </button>737 <button738 type="button"739 style={{740 border: '1px solid salmon',741 backgroundColor: '#fff',742 cursor: 'pointer',743 }}744 onClick={() => setCurrentTabIndex(2)}745 >746 Tab 3747 </button>748 </div>749 <div style={{ padding: 4 }}>750 Content of Tab {currentTabIndex + 1}751 <br /> <br />752 <button type="button" onClick={() => counterState.increment()}>753 Count: {counterState.count}754 </button>755 </div>756 </div>757 )758}759```760761Finally, we'll create the `App` component, which renders the tabs and their respective counters.762The counter state is managed independently for each tab.763764```tsx765export default function App() {766 return (767 <CounterStoresProvider>768 <Tabs />769 </CounterStoresProvider>770 )771}772```773774Here is what the code should look like:775776```tsx777import {778 type ReactNode,779 useState,780 useCallback,781 useContext,782 createContext,783} from 'react'784import { createStore, useStore } from 'zustand'785786type CounterState = {787 count: number788}789790type CounterActions = { increment: () => void }791792type CounterStore = CounterState & CounterActions793794const createCounterStore = () => {795 return createStore<CounterStore>()((set) => ({796 count: 0,797 increment: () => {798 set((state) => ({ count: state.count + 1 }))799 },800 }))801}802803const createCounterStoreFactory = (804 counterStores: Map<string, ReturnType<typeof createCounterStore>>,805) => {806 return (counterStoreKey: string) => {807 if (!counterStores.has(counterStoreKey)) {808 counterStores.set(counterStoreKey, createCounterStore())809 }810 return counterStores.get(counterStoreKey)!811 }812}813814const CounterStoresContext = createContext<Map<815 string,816 ReturnType<typeof createCounterStore>817> | null>(null)818819const CounterStoresProvider = ({ children }: { children: ReactNode }) => {820 const [stores] = useState(821 () => new Map<string, ReturnType<typeof createCounterStore>>(),822 )823824 return (825 <CounterStoresContext.Provider value={stores}>826 {children}827 </CounterStoresContext.Provider>828 )829}830831const useCounterStore = <U,>(832 key: string,833 selector: (state: CounterStore) => U,834) => {835 const stores = useContext(CounterStoresContext)836837 if (stores === undefined) {838 throw new Error('useCounterStore must be used within CounterStoresProvider')839 }840841 const getOrCreateCounterStoreByKey = useCallback(842 (key: string) => createCounterStoreFactory(stores!)(key),843 [stores],844 )845846 return useStore(getOrCreateCounterStoreByKey(key), selector)847}848849function Tabs() {850 const [currentTabIndex, setCurrentTabIndex] = useState(0)851 const counterState = useCounterStore(852 `tab-${currentTabIndex}`,853 (state) => state,854 )855856 return (857 <div style={{ fontFamily: 'monospace' }}>858 <div859 style={{860 display: 'flex',861 gap: '0.5rem',862 borderBottom: '1px solid salmon',863 paddingBottom: 4,864 }}865 >866 <button867 type="button"868 style={{869 border: '1px solid salmon',870 backgroundColor: '#fff',871 cursor: 'pointer',872 }}873 onClick={() => setCurrentTabIndex(0)}874 >875 Tab 1876 </button>877 <button878 type="button"879 style={{880 border: '1px solid salmon',881 backgroundColor: '#fff',882 cursor: 'pointer',883 }}884 onClick={() => setCurrentTabIndex(1)}885 >886 Tab 2887 </button>888 <button889 type="button"890 style={{891 border: '1px solid salmon',892 backgroundColor: '#fff',893 cursor: 'pointer',894 }}895 onClick={() => setCurrentTabIndex(2)}896 >897 Tab 3898 </button>899 </div>900 <div style={{ padding: 4 }}>901 Content of Tab {currentTabIndex + 1}902 <br /> <br />903 <button type="button" onClick={() => counterState.increment()}>904 Count: {counterState.count}905 </button>906 </div>907 </div>908 )909}910911export default function App() {912 return (913 <CounterStoresProvider>914 <Tabs />915 </CounterStoresProvider>916 )917}918```919920## Troubleshooting921922TBD
deleted:docs/integrations/immer-middleware.md-129 removed
1---2title: Immer middleware3nav: 184---56The [Immer](https://github.com/immerjs/immer) middleware enables you7to use immutable state in a more convenient way.8Also, with Immer, you can simplify handling9immutable data structures in Zustand.1011## Installation1213In order to use the Immer middleware in Zustand,14you will need to install Immer as a direct dependency.1516```bash17npm install immer18```1920## Usage2122(Notice the extra parentheses after the type parameter as mentioned in the [Advanced Typescript Guide](../guides/advanced-typescript.md)).2324Updating simple states2526```ts27import { create } from 'zustand'28import { immer } from 'zustand/middleware/immer'2930type State = {31 count: number32}3334type Actions = {35 increment: (qty: number) => void36 decrement: (qty: number) => void37}3839export const useCountStore = create<State & Actions>()(40 immer((set) => ({41 count: 0,42 increment: (qty: number) =>43 set((state) => {44 state.count += qty45 }),46 decrement: (qty: number) =>47 set((state) => {48 state.count -= qty49 }),50 })),51)52```5354Updating complex states5556```ts57import { create } from 'zustand'58import { immer } from 'zustand/middleware/immer'5960interface Todo {61 id: string62 title: string63 done: boolean64}6566type State = {67 todos: Record<string, Todo>68}6970type Actions = {71 toggleTodo: (todoId: string) => void72}7374export const useTodoStore = create<State & Actions>()(75 immer((set) => ({76 todos: {77 '82471c5f-4207-4b1d-abcb-b98547e01a3e': {78 id: '82471c5f-4207-4b1d-abcb-b98547e01a3e',79 title: 'Learn Zustand',80 done: false,81 },82 '354ee16c-bfdd-44d3-afa9-e93679bda367': {83 id: '354ee16c-bfdd-44d3-afa9-e93679bda367',84 title: 'Learn Jotai',85 done: false,86 },87 '771c85c5-46ea-4a11-8fed-36cc2c7be344': {88 id: '771c85c5-46ea-4a11-8fed-36cc2c7be344',89 title: 'Learn Valtio',90 done: false,91 },92 '363a4bac-083f-47f7-a0a2-aeeee153a99c': {93 id: '363a4bac-083f-47f7-a0a2-aeeee153a99c',94 title: 'Learn Signals',95 done: false,96 },97 },98 toggleTodo: (todoId: string) =>99 set((state) => {100 state.todos[todoId].done = !state.todos[todoId].done101 }),102 })),103)104```105106## Gotchas107108In this section you will find some things109that you need to keep in mind when using Zustand with Immer.110111### My subscriptions aren't being called112113If you are using Immer,114make sure you are actually following115[the rules of Immer](https://immerjs.github.io/immer/pitfalls).116117For example, you have to add `[immerable] = true` for118[class objects](https://immerjs.github.io/immer/complex-objects) to work.119If you don't do this, Immer will still mutate the object,120but not as a proxy, so it will also update the current state.121Zustand checks if the state has actually changed,122so since both the current state and the next state are123equal (if you don't do it correctly),124Zustand will skip calling the subscriptions.125126## Demos127128- Basic: https://stackblitz.com/edit/vitejs-vite-3sgc4ejy129- Advanced: https://stackblitz.com/edit/vitejs-vite-jxxtuyj3
deleted:docs/integrations/persisting-store-data.md-834 removed
1---2title: Persisting store data3nav: 204---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```
deleted:docs/integrations/third-party-libraries.md-82 removed
1---2title: Third-party Libraries3nav: 194---56Zustand provides bear necessities for state management.7Although it is great for most projects,8some users wish to extend the library's feature set.9This can be done using third-party libraries created by the community.1011> Disclaimer: These libraries may have bugs, limited maintenance,12> or other limitations, and are not officially recommended13> by pmndrs or the Zustand maintainers.14> This list aims to provide a good starting point15> for someone looking to extend Zustand's feature set.1617- [@colorfy-software/zfy](https://colorfy-software.gitbook.io/zfy/) — 🧸 Useful helpers for state management in React with Zustand.18- [@csark0812/zustand-expo-devtools](https://github.com/csark0812/zustand-expo-devtools) — 🧭 Connect Zustand to Redux DevTools in Expo + React Native using the official Expo DevTools plugin system.19- [@csark0812/zustand-getters](https://github.com/csark0812/zustand-getters) — 🔄 Make JavaScript object getters reactive in Zustand stores — define derived values with `get propertyName()` and they automatically trigger subscription updates when accessed.20- [@davstack/store](https://www.npmjs.com/package/@davstack/store) — A zustand store factory that auto generates selectors with get/set/use methods, supports inferred types, and makes global / local state management easy.21- [@dhmk/zustand-lens](https://github.com/dhmk083/dhmk-zustand-lens) — Lens support for Zustand.22- [@hpkv/zustand-multiplayer](https://github.com/hpkv-io/zustand-multiplayer/tree/main/packages/zustand-multiplayer) — HPKV multiplayer middleware for building realtime collaborative applications23- [@liveblocks/zustand](https://github.com/liveblocks/liveblocks/tree/main/packages/liveblocks-zustand) — Liveblocks middleware to make your application multiplayer.24- [@prncss-xyz/zustand-optics](https://github.com/prncss-xyz/zustand-optics) — An adapter for [optics-ts](https://github.com/akheron/optics-ts).25- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook) — Automatic generation of Zustand hooks with Typescript support.26- [derive-zustand](https://github.com/zustandjs/derive-zustand) — A function to create a derived Zustand store from other Zustand stores.27- [geschichte](https://github.com/BowlingX/geschichte) — Zustand and Immer-based hook to manage query parameters.28- [leiten-zustand](https://github.com/hecmatyar/leiten-zustand) — Cleans your store from boilerplate for requests and data transformation.29- [leo-query](https://github.com/steaks/leo-query) — A simple library to connect async queries to Zustand stores.30- [mobz](https://github.com/2A5F/Mobz) — Zustand-style MobX API.31- [ngx-zustand](https://github.com/JoaoPauloLousada/ngx-zustand) — A Zustand adapter for Angular.32- [persist-and-sync](https://github.com/mayank1513/persist-and-sync) — Zustand middleware to easily persist and sync Zustand state between tabs/windows/iframes with same origin.33- [shared-zustand](https://github.com/Tom-Julux/shared-zustand) — Cross-tab state sharing for Zustand.34- [simple-zustand-devtools](https://github.com/beerose/simple-zustand-devtools) — 🐻⚛️ Inspect your Zustand store in React DevTools.35- [solid-zustand](https://github.com/wobsoriano/solid-zustand) — State management in Solid using Zustand.36- [treeshakable](https://github.com/react18-tools/treeshakable) — A wrapper for library creators to avoid redundant store creation.37- [use-broadcast-ts](https://github.com/Romainlg29/use-broadcast) — Zustand middleware to share state between tabs.38- [use-post-message-ts](https://github.com/paulschoen/use-post-message) — Zustand middleware for sharing state between cross-origin iframes via postMessage browser method.39- [use-zustand](https://github.com/zustandjs/use-zustand) — Another custom hook to use Zustand vanilla store.40- [vue-zustand](https://github.com/wobsoriano/vue-zustand) — State management solution for Vue based on Zustand.41- [zoov](https://github.com/InfiniteXyy/zoov) — State management solution based on Zustand with Module-like API.42- [zubridge](https://github.com/goosewobbler/zubridge) — Use Zustand in cross-platform apps, seamlessly. Supports Electron & Tauri.43- [zukeeper](https://github.com/oslabs-beta/Zukeeper) — Native devtools with state and action tracking, diffing, tree display, and time travel44- [zundo](https://github.com/charkour/zundo) — 🍜 Undo and redo middleware for Zustand, enabling time-travel in your apps.45- [zustand-ards](https://github.com/ivoilic/zustand-ards) — 💁 Simple opinionated utilities for example alternative selector formats and default shallow hooks46- [zustand-async-slice](https://github.com/mym0404/zustand-async-slice) — Simple Zustand utility to create Async Slice. TypeScript Fully Supported 🖖47- [zustand-boilerplate](https://github.com/sagiereder/zustand-boilerplate) — A tool that automatically generates getters, setters and more for your zustand store.48- [zustand-computed](https://github.com/chrisvander/zustand-computed) — A Zustand middleware to create computed states.49- [zustand-computed-state](https://github.com/yasintz/zustand-computed-state) — Simple middleware to add computed states.50- [zustand-constate](https://github.com/ntvinhit/zustand-constate) — Context-based state management based on Zustand and taking ideas from Constate.51- [zustand-context](https://github.com/fredericoo/zustand-context) — Create a zustand store in React Context, containing an initial value, or use it in your components with isolated, mockable instances.52- [zustand-create-setter-fn](https://www.npmjs.com/package/zustand-create-setter-fn) — A fully type safe utility for Zustand that allows you to easily update state using React style `setState` functions (framework agnostic, doesn't require React).53- [zustand-di](https://github.com/charkour/zustand-di) — use react props to init zustand stores54- [zustand-forms](https://github.com/Conduct/zustand-forms) — Fast, type safe form states as Zustand stores.55- [zustand-hash-storage](https://github.com/MartinGamesCZ/zustand-hash-storage) — Zustand middleware for saving state into URL hash, b64 encoded (can be configured) and debounce timer.56- [zustand-injectors](https://github.com/zustandjs/zustand-injectors) — A sweet way to lazy load slices57- [zustand-interval-persist](https://www.npmjs.com/package/zustand-interval-persist) — An enhancement for zustand that enables automatic saving of the store's state to the specified storage at regular interval.58- [zustand-lit](https://github.com/ennjin/zustand-lit) — A zustand adapter for lit.js (LitElement)59- [zustand-middleware-computed-state](https://github.com/cmlarsen/zustand-middleware-computed-state) — A dead simple middleware for adding computed state to Zustand.60- [zustand-middleware-xstate](https://github.com/biowaffeln/zustand-middleware-xstate) — A middleware for putting XState state machines into a global Zustand store.61- [zustand-middleware-yjs](https://github.com/joebobmiles/zustand-middleware-yjs) — A middleware for synchronizing Zustand stores with Yjs.62- [zustand-mmkv-storage](https://github.com/1mehdifaraji/zustand-mmkv-storage) — Fast, lightweight MMKV storage adapter for Zustand persist middleware in React Native.63- [zustand-multi-persist](https://github.com/mooalot/zustand-multi-persist) — A middleware for persisting and rehydrating state to multiple storage engines.64- [zustand-mutable](https://github.com/zustandjs/zustand-mutable) — A sweet way to use immer-like mutable updates.65- [zustand-namespaces](https://github.com/mooalot/zustand-namespaces) — One store to rule them all. Namespaced Zustand stores.66- [zustand-persist](https://github.com/roadmanfong/zustand-persist) — A middleware for persisting and rehydrating state.67- [zustand-pub](https://github.com/AwesomeDevin/zustand-pub) — Cross-Application/Cross-Framework State Management And Sharing based on zustand and zustand-vue for React/Vue.68- [zustand-querystring](https://github.com/nitedani/zustand-querystring) — A Zustand middleware that syncs the store with the querystring.69- [zustand-rx](https://github.com/patdx/zustand-rx) — A Zustand middleware enabling you to subscribe to a store as an RxJS Observable.70- [zustand-saga](https://github.com/Nowsta/zustand-saga) — A Zustand middleware for redux-saga (minus redux).71- [zustand-slices](https://github.com/zustandjs/zustand-slices) — A slice utility for Zustand.72- [zustand-store-addons](https://github.com/Diablow/zustand-store-addons) — React state management addons for Zustand.73- [zustand-sync-tabs](https://github.com/mayank1513/zustand-sync-tabs) — Zustand middleware to easily sync Zustand state between tabs/windows/iframes with same origin.74- [zustand-utils](https://www.npmjs.com/package/zustand-utils) — Utilities for Zustand — a `createContext` replacement, a devtools wrapper, and a store-updater factory function.75- [zustand-valtio](https://github.com/zustandjs/zustand-valtio) — A sweet combination of Zustand and Valtio76- [zustand-vue](https://github.com/AwesomeDevin/zustand-vue) — State management for vue (Vue3 / Vue2) based on zustand.77- [zustand-x](https://github.com/udecode/zustand-x) — Zustand store factory for a best-in-class developer experience.78- [zustand-xs](https://github.com/zustandjs/zustand-xs) — XState/store compabile middleware for Zustand79- [zustand-yjs](https://github.com/tandem-pt/zustand-yjs) — Zustand stores for Yjs structures.80- [zusteller](https://github.com/timkindberg/zusteller) — Your global state savior. "Just hooks" + Zustand.81- [zustorm](https://github.com/mooalot/zustorm) — A simple and powerful form library for Zustand.82- [zusty](https://github.com/oslabs-beta/Zusty) — Zustand tool to assist debugging with time travel, action logs, state snapshots, store view, render time metrics and state component tree.
added:docs/learn/getting-started/comparison.md+483 added
1---2title: Comparison3description: How Zustand stacks up against similar libraries4nav: 25---67Zustand is one of many state management libraries for React.8On this page we will discuss Zustand9in comparison to some of these libraries,10including Redux, Valtio, Jotai, and Recoil.1112Each library has its own strengths and weaknesses,13and we will compare key differences and similarities between each.1415## Redux1617### State Model (vs Redux)1819Conceptually, Zustand and Redux are quite similar,20both are based on an immutable state model.21However, Redux requires your app to be wrapped22in context providers; Zustand does not.2324**Zustand**2526```ts27import { create } from 'zustand'2829type State = {30 count: number31}3233type Actions = {34 increment: (qty: number) => void35 decrement: (qty: number) => void36}3738const useCountStore = create<State & Actions>((set) => ({39 count: 0,40 increment: (qty: number) => set((state) => ({ count: state.count + qty })),41 decrement: (qty: number) => set((state) => ({ count: state.count - qty })),42}))43```4445```ts46import { create } from 'zustand'4748type State = {49 count: number50}5152type Action = {53 type: 'increment' | 'decrement'54 qty: number55}5657type Actions = {58 dispatch: (action: Action) => void59}6061const countReducer = (state: State, action: Action) => {62 switch (action.type) {63 case 'increment':64 return { count: state.count + action.qty }65 case 'decrement':66 return { count: state.count - action.qty }67 default:68 return state69 }70}7172const useCountStore = create<State & Actions>((set) => ({73 count: 0,74 dispatch: (action: Action) => set((state) => countReducer(state, action)),75}))76```7778**Redux**7980```ts81import { createStore } from 'redux'82import { useSelector, useDispatch } from 'react-redux'8384type State = {85 count: number86}8788type Action = {89 type: 'increment' | 'decrement'90 qty: number91}9293const countReducer = (state: State, action: Action) => {94 switch (action.type) {95 case 'increment':96 return { count: state.count + action.qty }97 case 'decrement':98 return { count: state.count - action.qty }99 default:100 return state101 }102}103104const countStore = createStore(countReducer)105```106107```ts108import { createSlice, configureStore } from '@reduxjs/toolkit'109110const countSlice = createSlice({111 name: 'count',112 initialState: { value: 0 },113 reducers: {114 incremented: (state, qty: number) => {115 // Redux Toolkit does not mutate the state, it uses the Immer library116 // behind scenes, allowing us to have something called "draft state".117 state.value += qty118 },119 decremented: (state, qty: number) => {120 state.value -= qty121 },122 },123})124125const countStore = configureStore({ reducer: countSlice.reducer })126```127128### Render Optimization (vs Redux)129130When it comes to render optimizations within your app,131there are no major differences in approach between Zustand and Redux.132In both libraries it is recommended133that you manually apply render optimizations by using selectors.134135**Zustand**136137```ts138import { create } from 'zustand'139140type State = {141 count: number142}143144type Actions = {145 increment: (qty: number) => void146 decrement: (qty: number) => void147}148149const useCountStore = create<State & Actions>((set) => ({150 count: 0,151 increment: (qty: number) => set((state) => ({ count: state.count + qty })),152 decrement: (qty: number) => set((state) => ({ count: state.count - qty })),153}))154155const Component = () => {156 const count = useCountStore((state) => state.count)157 const increment = useCountStore((state) => state.increment)158 const decrement = useCountStore((state) => state.decrement)159 // ...160}161```162163**Redux**164165```ts166import { createStore } from 'redux'167import { useSelector, useDispatch } from 'react-redux'168169type State = {170 count: number171}172173type Action = {174 type: 'increment' | 'decrement'175 qty: number176}177178const countReducer = (state: State, action: Action) => {179 switch (action.type) {180 case 'increment':181 return { count: state.count + action.qty }182 case 'decrement':183 return { count: state.count - action.qty }184 default:185 return state186 }187}188189const countStore = createStore(countReducer)190191const Component = () => {192 const count = useSelector((state) => state.count)193 const dispatch = useDispatch()194 // ...195}196```197198```ts199import { useSelector } from 'react-redux'200import type { TypedUseSelectorHook } from 'react-redux'201import { createSlice, configureStore } from '@reduxjs/toolkit'202203const countSlice = createSlice({204 name: 'count',205 initialState: { value: 0 },206 reducers: {207 incremented: (state, qty: number) => {208 // Redux Toolkit does not mutate the state, it uses the Immer library209 // behind scenes, allowing us to have something called "draft state".210 state.value += qty211 },212 decremented: (state, qty: number) => {213 state.value -= qty214 },215 },216})217218const countStore = configureStore({ reducer: countSlice.reducer })219220const useAppSelector: TypedUseSelectorHook<typeof countStore.getState> =221 useSelector222223const useAppDispatch: () => typeof countStore.dispatch = useDispatch224225const Component = () => {226 const count = useAppSelector((state) => state.count.value)227 const dispatch = useAppDispatch()228 // ...229}230```231232## Valtio233234### State Model (vs Valtio)235236Zustand and Valtio approach state management237in a fundamentally different way.238Zustand is based on the **immutable** state model,239while Valtio is based on the **mutable** state model.240241**Zustand**242243```ts244import { create } from 'zustand'245246type State = {247 obj: { count: number }248}249250const store = create<State>(() => ({ obj: { count: 0 } }))251252store.setState((prev) => ({ obj: { count: prev.obj.count + 1 } }))253```254255**Valtio**256257```ts258import { proxy } from 'valtio'259260const state = proxy({ obj: { count: 0 } })261262state.obj.count += 1263```264265### Render Optimization (vs Valtio)266267The other difference between Zustand and Valtio268is Valtio makes render optimizations through property access.269However, with Zustand, it is recommended that270you manually apply render optimizations by using selectors.271272**Zustand**273274```ts275import { create } from 'zustand'276277type State = {278 count: number279}280281const useCountStore = create<State>(() => ({282 count: 0,283}))284285const Component = () => {286 const count = useCountStore((state) => state.count)287 // ...288}289```290291**Valtio**292293```ts294import { proxy, useSnapshot } from 'valtio'295296const state = proxy({297 count: 0,298})299300const Component = () => {301 const { count } = useSnapshot(state)302 // ...303}304```305306## Jotai307308### State Model (vs Jotai)309310There is one major difference between Zustand and Jotai.311Zustand is a single store,312while Jotai consists of primitive atoms that can be composed together.313314**Zustand**315316```ts317import { create } from 'zustand'318319type State = {320 count: number321}322323type Actions = {324 updateCount: (325 countCallback: (count: State['count']) => State['count'],326 ) => void327}328329const useCountStore = create<State & Actions>((set) => ({330 count: 0,331 updateCount: (countCallback) =>332 set((state) => ({ count: countCallback(state.count) })),333}))334```335336**Jotai**337338```ts339import { atom } from 'jotai'340341const countAtom = atom<number>(0)342```343344### Render Optimization (vs Jotai)345346Jotai achieves render optimizations through atom dependency.347However, with Zustand it is recommended that348you manually apply render optimizations by using selectors.349350**Zustand**351352```ts353import { create } from 'zustand'354355type State = {356 count: number357}358359type Actions = {360 updateCount: (361 countCallback: (count: State['count']) => State['count'],362 ) => void363}364365const useCountStore = create<State & Actions>((set) => ({366 count: 0,367 updateCount: (countCallback) =>368 set((state) => ({ count: countCallback(state.count) })),369}))370371const Component = () => {372 const count = useCountStore((state) => state.count)373 const updateCount = useCountStore((state) => state.updateCount)374 // ...375}376```377378**Jotai**379380```ts381import { atom, useAtom } from 'jotai'382383const countAtom = atom<number>(0)384385const Component = () => {386 const [count, updateCount] = useAtom(countAtom)387 // ...388}389```390391## Recoil392393### State Model (vs Recoil)394395The difference between Zustand and Recoil396is similar to that between Zustand and Jotai.397Recoil depends on atom string keys398instead of atom object referential identities.399Additionally, Recoil needs to wrap your app in a context provider.400401**Zustand**402403```ts404import { create } from 'zustand'405406type State = {407 count: number408}409410type Actions = {411 setCount: (countCallback: (count: State['count']) => State['count']) => void412}413414const useCountStore = create<State & Actions>((set) => ({415 count: 0,416 setCount: (countCallback) =>417 set((state) => ({ count: countCallback(state.count) })),418}))419```420421**Recoil**422423```ts424import { atom } from 'recoil'425426const count = atom({427 key: 'count',428 default: 0,429})430```431432### Render Optimization (vs Recoil)433434Similar to previous optimization comparisons,435Recoil makes render optimizations through atom dependency.436Whereas with Zustand, it is recommended that437you manually apply render optimizations by using selectors.438439**Zustand**440441```ts442import { create } from 'zustand'443444type State = {445 count: number446}447448type Actions = {449 setCount: (countCallback: (count: State['count']) => State['count']) => void450}451452const useCountStore = create<State & Actions>((set) => ({453 count: 0,454 setCount: (countCallback) =>455 set((state) => ({ count: countCallback(state.count) })),456}))457458const Component = () => {459 const count = useCountStore((state) => state.count)460 const setCount = useCountStore((state) => state.setCount)461 // ...462}463```464465**Recoil**466467```ts468import { atom, useRecoilState } from 'recoil'469470const countAtom = atom({471 key: 'count',472 default: 0,473})474475const Component = () => {476 const [count, setCount] = useRecoilState(countAtom)477 // ...478}479```480481## Npm Downloads Trend482483- [Npm Downloads Trend of State Management Libraries for React](https://npm-stat.com/charts.html?package=zustand&package=jotai&package=valtio&package=%40reduxjs%2Ftoolkit&package=recoil)
added:docs/learn/getting-started/introduction.md+72 added
1---2title: Introduction3description: How to use Zustand4nav: 15---67<div class="flex justify-center mb-4">8 <img src="/bear.jpg" alt="Logo Zustand" />9</div>1011A small, fast, and scalable bearbones state management solution.12Zustand has a comfy API based on hooks.13It isn't boilerplatey or opinionated,14but has enough convention to be explicit and flux-like.1516Don't disregard it because it's cute, it has claws!17Lots of time was spent to deal with common pitfalls,18like the dreaded [zombie child problem],19[React concurrency], and [context loss]20between mixed renderers.21It may be the one state manager in the React space that gets all of these right.2223You can try a live demo [here](https://codesandbox.io/s/dazzling-moon-itop4).2425[zombie child problem]: https://react-redux.js.org/api/hooks#stale-props-and-zombie-children26[react concurrency]: https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md27[context loss]: https://github.com/facebook/react/issues/133322829## Installation3031Zustand is available as a package on NPM for use:3233```bash34# NPM35npm install zustand36# Or, use any package manager of your choice.37```3839## First create a store4041Your store is a hook!42You can put anything in it: primitives, objects, functions.43The `set` function _merges_ state.4445```js46import { create } from 'zustand'4748const useBear = create((set) => ({49 bears: 0,50 increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),51 removeAllBears: () => set({ bears: 0 }),52 updateBears: (newBears) => set({ bears: newBears }),53}))54```5556## Then bind your components, and that's it!5758You can use the hook anywhere, without the need of providers.59Select your state and the consuming component60will re-render when that state changes.6162```jsx63function BearCounter() {64 const bears = useBear((state) => state.bears)65 return <h1>{bears} bears around here...</h1>66}6768function Controls() {69 const increasePopulation = useBear((state) => state.increasePopulation)70 return <button onClick={increasePopulation}>one up</button>71}72```
added:docs/learn/guides/advanced-typescript.md+542 added
1---2title: Advanced TypeScript Guide3nav: 134---56## Basic usage78The difference when using TypeScript is that instead of writing `create(...)`, you have to write `create<T>()(...)` (notice the extra parentheses `()` too along with the type parameter) where `T` is the type of the state to annotate it. For example:910```ts11import { create } from 'zustand'1213interface BearState {14 bears: number15 increase: (by: number) => void16}1718const useBearStore = create<BearState>()((set) => ({19 bears: 0,20 increase: (by) => set((state) => ({ bears: state.bears + by })),21}))22```2324<details>25 <summary>Why can't we simply infer the type from the initial state?</summary>2627 <br/>2829**TLDR**: Because state generic `T` is invariant.3031Consider this minimal version `create`:3233```ts34declare const create: <T>(f: (get: () => T) => T) => T3536const x = create((get) => ({37 foo: 0,38 bar: () => get(),39}))40// `x` is inferred as `unknown` instead of41// interface X {42// foo: number,43// bar: () => X44// }45```4647Here, if you look at the type of `f` in `create`, i.e. `(get: () => T) => T`, it "gives" `T` via return (making it covariant), but it also "takes" `T` via `get` (making it contravariant). "So where does `T` come from?" TypeScript wonders. It's like that chicken or egg problem. At the end TypeScript, gives up and infers `T` as `unknown`.4849So, as long as the generic to be inferred is invariant (i.e. both covariant and contravariant), TypeScript will be unable to infer it. Another simple example would be this:5051```ts52const createFoo = {} as <T>(f: (t: T) => T) => T53const x = createFoo((_) => 'hello')54```5556Here again, `x` is `unknown` instead of `string`.5758 <details>59 <summary>More about the inference (just for the people curious and interested in TypeScript)</summary>6061In some sense this inference failure is not a problem because a value of type `<T>(f: (t: T) => T) => T` cannot be written. That is to say you can't write the real runtime implementation of `createFoo`. Let's try it:6263```js64const createFoo = (f) => f(/* ? */)65```6667`createFoo` needs to return the return value of `f`. And to do that we first have to call `f`. And to call it we have to pass a value of type `T`. And to pass a value of type `T` we first have to produce it. But how can we produce a value of type `T` when we don't even know what `T` is? The only way to produce a value of type `T` is to call `f`, but then to call `f` itself we need a value of type `T`. So you see it's impossible to actually write `createFoo`.6869So what we're saying is, the inference failure in case of `createFoo` is not really a problem because it's impossible to implement `createFoo`. But what about the inference failure in case of `create`? That also is not really a problem because it's impossible to implement `create` too. Wait a minute, if it's impossible to implement `create` then how does Zustand implement it? The answer is, it doesn't.7071Zustand lies that it implemented `create`'s type, it implemented only the most part of it. Here's a simple proof by showing unsoundness. Consider the following code:7273```ts74import { create } from 'zustand'7576const useBoundStore = create<{ foo: number }>()((_, get) => ({77 foo: get().foo,78}))79```8081This code compiles. But if we run it, we'll get an exception: "Uncaught TypeError: Cannot read properties of undefined (reading 'foo')". This is because `get` would return `undefined` before the initial state is created (hence you shouldn't call `get` when creating the initial state). The types promise that `get` will never return `undefined` but it does initially, which means Zustand failed to implement it.8283And of course Zustand failed because it's impossible to implement `create` the way types promise (in the same way it's impossible to implement `createFoo`). In other words we don't have a type to express the actual `create` we have implemented. We can't type `get` as `() => T | undefined` because it would cause inconvenience and it still won't be correct as `get` is indeed `() => T` eventually, just if called synchronously it would be `() => undefined`. What we need is some kind of TypeScript feature that allows us to type `get` as `(() => T) & WhenSync<() => undefined>`, which of course is extremely far-fetched.8485So we have two problems: lack of inference and unsoundness. Lack of inference can be solved if TypeScript can improve its inference for invariants. And unsoundness can be solved if TypeScript introduces something like `WhenSync`. To work around lack of inference we manually annotate the state type. And we can't work around unsoundness, but it's not a big deal because it's not much, calling `get` synchronously anyway doesn't make sense.8687</details>8889</details>9091<details>92 <summary>Why the currying `()(...)`?</summary>9394 <br/>9596**TLDR**: It is a workaround for [microsoft/TypeScript#10571](https://github.com/microsoft/TypeScript/issues/10571).9798Imagine you have a scenario like this:99100```ts101declare const withError: <T, E>(102 p: Promise<T>,103) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>104declare const doSomething: () => Promise<string>105106const main = async () => {107 let [error, value] = await withError(doSomething())108}109```110111Here, `T` is inferred to be a `string` and `E` is inferred to be `unknown`. You might want to annotate `E` as `Foo`, because you are certain of the shape of error `doSomething()` would throw. However, you can't do that. You can either pass all generics or none. Along with annotating `E` as `Foo`, you will also have to annotate `T` as `string` even though it gets inferred anyway. The solution is to make a curried version of `withError` that does nothing at runtime. Its purpose is to just allow you annotate `E`.112113```ts114declare const withError: {115 <E>(): <T>(116 p: Promise<T>,117 ) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>118 <T, E>(119 p: Promise<T>,120 ): Promise<[error: undefined, value: T] | [error: E, value: undefined]>121}122declare const doSomething: () => Promise<string>123interface Foo {124 bar: string125}126127const main = async () => {128 let [error, value] = await withError<Foo>()(doSomething())129}130```131132This way, `T` gets inferred and you get to annotate `E`. Zustand has the same use case when we want to annotate the state (the first type parameter) but allow other parameters to get inferred.133134</details>135136Alternatively, you can also use `combine`, which infers the state so that you do not need to type it.137138```ts139import { create } from 'zustand'140import { combine } from 'zustand/middleware'141142const useBearStore = create(143 combine({ bears: 0 }, (set) => ({144 increase: (by: number) => set((state) => ({ bears: state.bears + by })),145 })),146)147```148149<details>150 <summary>Be a little careful</summary>151152 <br/>153154We achieve the inference by lying a little in the types of `set`, `get`, and `store` that you receive as parameters. The lie is that they're typed as if the state is the first parameter, when in fact the state is the shallow-merge (`{ ...a, ...b }`) of both first parameter and the second parameter's return. For example, `get` from the second parameter has type `() => { bears: number }` and that is a lie as it should be `() => { bears: number, increase: (by: number) => void }`. And `useBearStore` still has the correct type; for example, `useBearStore.getState` is typed as `() => { bears: number, increase: (by: number) => void }`.155156It isn't really a lie because `{ bears: number }` is still a subtype of `{ bears: number, increase: (by: number) => void }`. Therefore, there will be no problem in most cases. You should just be careful while using replace. For example, `set({ bears: 0 }, true)` would compile but will be unsound as it will delete the `increase` function. Another instance where you should be careful is if you use `Object.keys`. `Object.keys(get())` will return `["bears", "increase"]` and not `["bears"]`. The return type of `get` can make you fall for these mistakes.157158`combine` trades off a little type-safety for the convenience of not having to write a type for state. Hence, you should use `combine` accordingly. It is fine in most cases and you can use it conveniently.159160</details>161162Note that we don't use the curried version when using `combine` because `combine` "creates" the state. When using a middleware that creates the state, it isn't necessary to use the curried version because the state now can be inferred. Another middleware that creates state is `redux`. So when using `combine`, `redux`, or any other custom middleware that creates the state, we don't recommend using the curried version.163164If you want to infer state type also outside of state declaration, you can use the `ExtractState` type helper:165166```ts167import { create, ExtractState } from 'zustand'168import { combine } from 'zustand/middleware'169170type BearState = ExtractState<typeof useBearStore>171172const useBearStore = create(173 combine({ bears: 0 }, (set) => ({174 increase: (by: number) => set((state) => ({ bears: state.bears + by })),175 })),176)177```178179## Using middlewares180181You do not have to do anything special to use middlewares in TypeScript.182183```ts184import { create } from 'zustand'185import { devtools, persist } from 'zustand/middleware'186187interface BearState {188 bears: number189 increase: (by: number) => void190}191192const useBearStore = create<BearState>()(193 devtools(194 persist(195 (set) => ({196 bears: 0,197 increase: (by) => set((state) => ({ bears: state.bears + by })),198 }),199 { name: 'bearStore' },200 ),201 ),202)203```204205Just make sure you are using them immediately inside `create` so as to make the contextual inference work. Doing something even remotely fancy like the following `myMiddlewares` would require more advanced types.206207```ts208import { create } from 'zustand'209import { devtools, persist } from 'zustand/middleware'210211const myMiddlewares = (f) => devtools(persist(f, { name: 'bearStore' }))212213interface BearState {214 bears: number215 increase: (by: number) => void216}217218const useBearStore = create<BearState>()(219 myMiddlewares((set) => ({220 bears: 0,221 increase: (by) => set((state) => ({ bears: state.bears + by })),222 })),223)224```225226Also, we recommend using `devtools` middleware as last as possible. For example, when you use it with `immer` as a middleware, it should be `devtools(immer(...))` and not `immer(devtools(...))`. This is because`devtools` mutates the `setState` and adds a type parameter on it, which could get lost if other middlewares (like `immer`) also mutate `setState` before `devtools`. Hence using `devtools` at the end makes sure that no middlewares mutate `setState` before it.227228## Authoring middlewares and advanced usage229230Imagine you had to write this hypothetical middleware.231232```ts233import { create } from 'zustand'234235const foo = (f, bar) => (set, get, store) => {236 store.foo = bar237 return f(set, get, store)238}239240const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))241console.log(useBearStore.foo.toUpperCase())242```243244Zustand middlewares can mutate the store. But how could we possibly encode the mutation on the type-level? That is to say how could we type `foo` so that this code compiles?245246For a usual statically typed language, this is impossible. But thanks to TypeScript, Zustand has something called a "higher-kinded mutator" that makes this possible. If you are dealing with complex type problems, like typing a middleware or using the `StateCreator` type, you will have to understand this implementation detail. For this, you can [check out #710](https://github.com/pmndrs/zustand/issues/710).247248If you are eager to know what the answer is to this particular problem then you can [see it here](#middleware-that-changes-the-store-type).249250### Handling Dynamic `replace` Flag251252If the value of the `replace` flag is not known at compile time and is determined dynamically, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:253254```ts255const replaceFlag = Math.random() > 0.5256const args = [{ bears: 5 }, replaceFlag] as Parameters<257 typeof useBearStore.setState258>259store.setState(...args)260```261262#### Example with `as Parameters` Workaround263264```ts265import { create } from 'zustand'266267interface BearState {268 bears: number269 increase: (by: number) => void270}271272const useBearStore = create<BearState>()((set) => ({273 bears: 0,274 increase: (by) => set((state) => ({ bears: state.bears + by })),275}))276277const replaceFlag = Math.random() > 0.5278const args = [{ bears: 5 }, replaceFlag] as Parameters<279 typeof useBearStore.setState280>281useBearStore.setState(...args) // Using the workaround282```283284By following this approach, you can ensure that your code handles dynamic `replace` flags without encountering type issues.285286## Common recipes287288### Middleware that doesn't change the store type289290```ts291import { create, StateCreator, StoreMutatorIdentifier } from 'zustand'292293type Logger = <294 T,295 Mps extends [StoreMutatorIdentifier, unknown][] = [],296 Mcs extends [StoreMutatorIdentifier, unknown][] = [],297>(298 f: StateCreator<T, Mps, Mcs>,299 name?: string,300) => StateCreator<T, Mps, Mcs>301302type LoggerImpl = <T>(303 f: StateCreator<T, [], []>,304 name?: string,305) => StateCreator<T, [], []>306307const loggerImpl: LoggerImpl = (f, name) => (set, get, store) => {308 const loggedSet: typeof set = (...a) => {309 set(...(a as Parameters<typeof set>))310 console.log(...(name ? [`${name}:`] : []), get())311 }312 const setState = store.setState313 store.setState = (...a) => {314 setState(...(a as Parameters<typeof setState>))315 console.log(...(name ? [`${name}:`] : []), store.getState())316 }317318 return f(loggedSet, get, store)319}320321export const logger = loggerImpl as unknown as Logger322323// ---324325const useBearStore = create<BearState>()(326 logger(327 (set) => ({328 bears: 0,329 increase: (by) => set((state) => ({ bears: state.bears + by })),330 }),331 'bear-store',332 ),333)334```335336### Middleware that changes the store type337338```ts339import {340 create,341 StateCreator,342 StoreMutatorIdentifier,343 Mutate,344 StoreApi,345} from 'zustand'346347type Foo = <348 T,349 A,350 Mps extends [StoreMutatorIdentifier, unknown][] = [],351 Mcs extends [StoreMutatorIdentifier, unknown][] = [],352>(353 f: StateCreator<T, [...Mps, ['foo', A]], Mcs>,354 bar: A,355) => StateCreator<T, Mps, [['foo', A], ...Mcs]>356357declare module 'zustand' {358 interface StoreMutators<S, A> {359 foo: Write<Cast<S, object>, { foo: A }>360 }361}362363type FooImpl = <T, A>(364 f: StateCreator<T, [], []>,365 bar: A,366) => StateCreator<T, [], []>367368const fooImpl: FooImpl = (f, bar) => (set, get, _store) => {369 type T = ReturnType<typeof f>370 type A = typeof bar371372 const store = _store as Mutate<StoreApi<T>, [['foo', A]]>373 store.foo = bar374 return f(set, get, _store)375}376377export const foo = fooImpl as unknown as Foo378379type Write<T extends object, U extends object> = Omit<T, keyof U> & U380381type Cast<T, U> = T extends U ? T : U382383// ---384385const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))386console.log(useBearStore.foo.toUpperCase())387```388389### `create` without curried workaround390391The recommended way to use `create` is using the curried workaround like so: `create<T>()(...)`. This is because it enables you to infer the store type. But if for some reason you do not want to use the workaround, you can pass the type parameters like the following. Note that in some cases, this acts as an assertion instead of annotation, so we don't recommend it.392393```ts394import { create } from "zustand"395396interface BearState {397 bears: number398 increase: (by: number) => void399}400401const useBearStore = create<402 BearState,403 [404 ['zustand/persist', BearState],405 ['zustand/devtools', never]406 ]407>(devtools(persist((set) => ({408 bears: 0,409 increase: (by) => set((state) => ({ bears: state.bears + by })),410}), { name: 'bearStore' }))411```412413### Slices pattern414415```ts416import { create, StateCreator } from 'zustand'417418interface BearSlice {419 bears: number420 addBear: () => void421 eatFish: () => void422}423424interface FishSlice {425 fishes: number426 addFish: () => void427}428429interface SharedSlice {430 addBoth: () => void431 getBoth: () => number432}433434const createBearSlice: StateCreator<435 BearSlice & FishSlice,436 [],437 [],438 BearSlice439> = (set) => ({440 bears: 0,441 addBear: () => set((state) => ({ bears: state.bears + 1 })),442 eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),443})444445const createFishSlice: StateCreator<446 BearSlice & FishSlice,447 [],448 [],449 FishSlice450> = (set) => ({451 fishes: 0,452 addFish: () => set((state) => ({ fishes: state.fishes + 1 })),453})454455const createSharedSlice: StateCreator<456 BearSlice & FishSlice,457 [],458 [],459 SharedSlice460> = (set, get) => ({461 addBoth: () => {462 // you can reuse previous methods463 get().addBear()464 get().addFish()465 // or do them from scratch466 // set((state) => ({ bears: state.bears + 1, fishes: state.fishes + 1 })467 },468 getBoth: () => get().bears + get().fishes,469})470471const useBoundStore = create<BearSlice & FishSlice & SharedSlice>()((...a) => ({472 ...createBearSlice(...a),473 ...createFishSlice(...a),474 ...createSharedSlice(...a),475}))476```477478A detailed explanation on the slices pattern can be found [here](./slices-pattern.md).479480If you have some middlewares then replace `StateCreator<MyState, [], [], MySlice>` with `StateCreator<MyState, Mutators, [], MySlice>`. For example, if you are using `devtools` then it will be `StateCreator<MyState, [["zustand/devtools", never]], [], MySlice>`. See the ["Middlewares and their mutators reference"](#middlewares-and-their-mutators-reference) section for a list of all mutators.481482### Bounded `useStore` hook for vanilla stores483484```ts485import { useStore } from 'zustand'486import { createStore } from 'zustand/vanilla'487488interface BearState {489 bears: number490 increase: (by: number) => void491}492493const bearStore = createStore<BearState>()((set) => ({494 bears: 0,495 increase: (by) => set((state) => ({ bears: state.bears + by })),496}))497498function useBearStore(): BearState499function useBearStore<T>(selector: (state: BearState) => T): T500function useBearStore<T>(selector?: (state: BearState) => T) {501 return useStore(bearStore, selector!)502}503```504505You can also make an abstract `createBoundedUseStore` function if you need to create bounded `useStore` hooks often and want to DRY things up...506507```ts508import { useStore, StoreApi } from 'zustand'509import { createStore } from 'zustand/vanilla'510511interface BearState {512 bears: number513 increase: (by: number) => void514}515516const bearStore = createStore<BearState>()((set) => ({517 bears: 0,518 increase: (by) => set((state) => ({ bears: state.bears + by })),519}))520521const createBoundedUseStore = ((store) => (selector) =>522 useStore(store, selector)) as <S extends StoreApi<unknown>>(523 store: S,524) => {525 (): ExtractState<S>526 <T>(selector: (state: ExtractState<S>) => T): T527}528529type ExtractState<S> = S extends { getState: () => infer X } ? X : never530531const useBearStore = createBoundedUseStore(bearStore)532```533534## Middlewares and their mutators reference535536- `devtools` — `["zustand/devtools", never]`537- `persist` — `["zustand/persist", YourPersistedState]`<br/>538 `YourPersistedState` is the type of state you are going to persist, ie the return type of `options.partialize`, if you're not passing `partialize` options the `YourPersistedState` becomes `Partial<YourState>`. Also [sometimes](https://github.com/pmndrs/zustand/issues/980#issuecomment-1162289836) passing actual `PersistedState` won't work. In those cases, try passing `unknown`.539- `immer` — `["zustand/immer", never]`540- `subscribeWithSelector` — `["zustand/subscribeWithSelector", never]`541- `redux` — `["zustand/redux", YourAction]`542- `combine` — no mutator as `combine` does not mutate the store
added:docs/learn/guides/auto-generating-selectors.md+134 added
1---2title: Auto Generating Selectors3nav: 144---56We recommend using selectors when using either the properties or actions from the store. You can access values from the store like so:78```typescript9const bears = useBearStore((state) => state.bears)10```1112However, writing these could be tedious. If that is the case for you, you can auto-generate your selectors.1314## Create the following function: `createSelectors`1516```typescript17import { StoreApi, UseBoundStore } from 'zustand'1819type WithSelectors<S> = S extends { getState: () => infer T }20 ? S & { use: { [K in keyof T]: () => T[K] } }21 : never2223const createSelectors = <S extends UseBoundStore<StoreApi<object>>>(24 _store: S,25) => {26 const store = _store as WithSelectors<typeof _store>27 store.use = {}28 for (const k of Object.keys(store.getState())) {29 ;(store.use as any)[k] = () => store((s) => s[k as keyof typeof s])30 }3132 return store33}34```3536If you have a store like this:3738```typescript39interface BearState {40 bears: number41 increase: (by: number) => void42 increment: () => void43}4445const useBearStoreBase = create<BearState>()((set) => ({46 bears: 0,47 increase: (by) => set((state) => ({ bears: state.bears + by })),48 increment: () => set((state) => ({ bears: state.bears + 1 })),49}))50```5152Apply that function to your store:5354```typescript55const useBearStore = createSelectors(useBearStoreBase)56```5758Now the selectors are auto generated and you can access them directly:5960```typescript61// get the property62const bears = useBearStore.use.bears()6364// get the action65const increment = useBearStore.use.increment()66```6768## Vanilla Store6970If you are using a vanilla store, use the following `createSelectors` function:7172```typescript73import { StoreApi, useStore } from 'zustand'7475type WithSelectors<S> = S extends { getState: () => infer T }76 ? S & { use: { [K in keyof T]: () => T[K] } }77 : never7879const createSelectors = <S extends StoreApi<object>>(_store: S) => {80 const store = _store as WithSelectors<typeof _store>81 store.use = {}82 for (const k of Object.keys(store.getState())) {83 ;(store.use as any)[k] = () =>84 useStore(_store, (s) => s[k as keyof typeof s])85 }8687 return store88}89```9091The usage is the same as a React store. If you have a store like this:9293```typescript94import { createStore } from 'zustand'9596interface BearState {97 bears: number98 increase: (by: number) => void99 increment: () => void100}101102const store = createStore<BearState>()((set) => ({103 bears: 0,104 increase: (by) => set((state) => ({ bears: state.bears + by })),105 increment: () => set((state) => ({ bears: state.bears + 1 })),106}))107```108109Apply that function to your store:110111```typescript112const useBearStore = createSelectors(store)113```114115Now the selectors are auto generated and you can access them directly:116117```typescript118// get the property119const bears = useBearStore.use.bears()120121// get the action122const increment = useBearStore.use.increment()123```124125## Live Demo126127For a working example of this, see the [Code Sandbox](https://codesandbox.io/s/zustand-auto-generate-selectors-forked-rl8v5e?file=/src/selectors.ts).128129## Third-party Libraries130131- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook)132- [react-hooks-global-state](https://github.com/dai-shi/react-hooks-global-state)133- [zustood](https://github.com/udecode/zustood)134- [@davstack/store](https://github.com/DawidWraga/davstack)
added:docs/learn/guides/beginner-typescript.md+378 added
1---2title: Beginner TypeScript Guide3nav: 124---56Zustand is a lightweight state manager, particularly used with React. Zustand avoids reducers, context, and boilerplate.7Paired with TypeScript, you get a strongly typed store-state, actions, and selectors-with autocomplete and compile-time safety.89In this basic guide we’ll cover:1011- Creating a typed store (state + actions)12- Using the store in React components with type safety13- Resetting the store safely with types14- Extracting and reusing Store type (for props, tests, and utilities)15- Composing multiple selectors and building derived state (with type inference and without extra re-renders)16- Middlewares with TypeScript support (`combine`, `devtools`, `persist`)17- Async actions with typed API responses18- Working with `createWithEqualityFn` (enhanced `create` store function)19- Structuring and coordinating multiple stores2021### Creating a Store with State & Actions2223Here we describe state and actions using an Typescript interface. The `<BearState>` generic forces the store to match this shape.24This means if you forget a field or use the wrong type, TypeScript will complain. Unlike plain JS, this guarantees type-safe state management.25The `create` function uses the curried form, which results in a store of type `UseBoundStore<StoreApi<BearState>>`.2627```ts28// store.ts29import { create } from 'zustand'3031// Define types for state & actions32interface BearState {33 bears: number34 food: string35 feed: (food: string) => void36}3738// Create store using the curried form of `create`39export const useBearStore = create<BearState>()((set) => ({40 bears: 2,41 food: 'honey',42 feed: (food) => set(() => ({ food })),43}))44```4546### Using the Store in Components4748Inside components, you can read state and call actions. Selectors `(s) => s.bears` subscribe to only what you need.49This reduces re-renders and improves performance. JS can do this too, but with TS your IDE autocompletes state fields.5051```tsx52import { useBearStore } from './store'5354function BearCounter() {55 // Select only 'bears' to avoid unnecessary re-renders56 const bears = useBearStore((s) => s.bears)57 return <h1>{bears} bears around</h1>58}59```6061### Resetting the Store6263Resetting is useful after logout or “clear session”. We use `typeof initialState` to avoid repeating property types.64TypeScript updates automatically if `initialState` changes. This is safer and cleaner compared to JS.6566```tsx67import { create } from 'zustand'6869const initialState = { bears: 0, food: 'honey' }7071// Reuse state type dynamically72type BearState = typeof initialState & {73 increase: (by: number) => void74 reset: () => void75}7677const useBearStore = create<BearState>()((set) => ({78 ...initialState,79 increase: (by) => set((s) => ({ bears: s.bears + by })),80 reset: () => set(initialState),81}))8283function ResetZoo() {84 const { bears, increase, reset } = useBearStore()8586 return (87 <div>88 <div>{bears}</div>89 <button onClick={() => increase(5)}>Increase by 5</button>90 <button onClick={reset}>Reset</button>91 </div>92 )93}94```9596### Extracting Types9798Zustand provides a built-in helper called `ExtractState`. This is useful for tests, utility functions, or component props.99It returns the full type of your store’s state and actions without having to manually redefine them. Extracting the Store type:100101```ts102// store.ts103import { create, type ExtractState } from 'zustand'104105export const useBearStore = create((set) => ({106 bears: 3,107 food: 'honey',108 increase: (by: number) => set((s) => ({ bears: s.bears + by })),109}))110111// Extract the type of the whole store state112export type BearState = ExtractState<typeof useBearStore>113```114115Using extracted type in tests:116117```ts118// test.cy.ts119import { BearState } from './store.ts'120121test('should reset store', () => {122 const snapshot: BearState = useBearStore.getState()123 expect(snapshot.bears).toBeGreaterThanOrEqual(0)124})125```126127and in utility function:128129```ts130// util.ts131import { BearState } from './store.ts'132133function logBearState(state: BearState) {134 console.log(`We have ${state.bears} bears eating ${state.food}`)135}136137logBearState(useBearStore.getState())138```139140### Selectors141142#### Multiple Selectors143144Sometimes you need more than one property. Returning an object from the selector lets you access multiple fields at once.145However, directly destructuring properties from that object can cause unnecessary re-renders.146To avoid this, it’s recommended to wrap the selector with `useShallow`, which prevents re-renders when the selected values remain shallowly equal.147This is more efficient than subscribing to the whole store. TypeScript ensures you can’t accidentally misspell `bears` or `food`.148See the [API documentation](https://zustand.docs.pmnd.rs/hooks/use-shallow) for more details on `useShallow`.149150```tsx151import { create } from 'zustand'152import { useShallow } from 'zustand/react/shallow'153154// Bear store with explicit types155interface BearState {156 bears: number157 food: number158}159160const useBearStore = create<BearState>()(() => ({161 bears: 2,162 food: 10,163}))164165// In components, you can use both stores safely166function MultipleSelectors() {167 const { bears, food } = useBearStore(168 useShallow((state) => ({ bears: state.bears, food: state.food })),169 )170171 return (172 <div>173 We have {food} units of food for {bears} bears174 </div>175 )176}177```178179#### Derived State with Selectors180181Not all values need to be stored directly - some can be computed from existing state. You can derive values using selectors.182This avoids duplication and keeps the store minimal. TypeScript ensures `bears` is a number, so math is safe.183184```tsx185import { create } from 'zustand'186187interface BearState {188 bears: number189 foodPerBear: number190}191192const useBearStore = create<BearState>()(() => ({193 bears: 3,194 foodPerBear: 2,195}))196197function TotalFood() {198 // Derived value: required amount food for all bears199 const totalFood = useBearStore((s) => s.bears * s.foodPerBear) // don't need to have extra property `{ totalFood: 6 }` in your Store200201 return <div>We need ${totalFood} jars of honey</div>202}203```204205### Middlewares206207#### `combine` middleware208209This middleware separates initial state and actions, making the code cleaner.210TS automatically infers types from the state and actions, no interface needed.211This is different from JS, where type safety is missing. It’s a very popular style in TypeScript projects.212See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/combine) for more details.213214```ts215import { create } from 'zustand'216import { combine } from 'zustand/middleware'217218interface BearState {219 bears: number220 increase: () => void221}222223// State + actions are separated224export const useBearStore = create<BearState>()(225 combine({ bears: 0 }, (set) => ({226 increase: () => set((s) => ({ bears: s.bears + 1 })),227 })),228)229```230231#### `devtools` middleware232233This middleware connects Zustand to Redux DevTools. You can inspect changes, time-travel, and debug state.234It’s extremely useful in development. TS ensures your actions and state remain type-checked even here.235See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/devtools) for more details.236237```ts238import { create } from 'zustand'239import { devtools } from 'zustand/middleware'240241interface BearState {242 bears: number243 increase: () => void244}245246export const useBearStore = create<BearState>()(247 devtools((set) => ({248 bears: 0,249 increase: () => set((s) => ({ bears: s.bears + 1 })),250 })),251)252```253254#### `persist` middleware255256This middleware keeps your store in `localStorage` (or another storage). This means your bears survive a page refresh.257Great for apps where persistence matters. In TS, the state type stays consistent, so no runtime surprises.258See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/persist) for more details.259260```ts261import { create } from 'zustand'262import { persist } from 'zustand/middleware'263264interface BearState {265 bears: number266 increase: () => void267}268269export const useBearStore = create<BearState>()(270 persist(271 (set) => ({272 bears: 0,273 increase: () => set((s) => ({ bears: s.bears + 1 })),274 }),275 { name: 'bear-storage' }, // localStorage key276 ),277)278```279280### Async Actions281282Actions can be async to fetch remote data. Here we fetch bears count and update state.283TS enforces correct API response type (`BearData`). In JS you might misspell `count` - TS prevents that.284285```ts286import { create } from 'zustand'287288interface BearData {289 count: number290}291292interface BearState {293 bears: number294 fetchBears: () => Promise<void>295}296297export const useBearStore = create<BearState>()((set) => ({298 bears: 0,299 fetchBears: async () => {300 const res = await fetch('/api/bears')301 const data: BearData = await res.json()302303 set({ bears: data.count })304 },305}))306```307308### `createWithEqualityFn`309310Variant of `create` with equality built-in. Useful if you always want custom equality checks.311Not common, but shows Zustand’s flexibility. TS still keeps full type inference.312See the [API documentation](https://zustand.docs.pmnd.rs/apis/create-with-equality-fn) for more details.313314```ts315import { createWithEqualityFn } from 'zustand/traditional'316import { shallow } from 'zustand/shallow'317318const useBearStore = createWithEqualityFn(() => ({319 bears: 0,320}))321322const bears = useBearStore((s) => s.bears, Object.is)323// or324const bears = useBearStore((s) => ({ bears: s.bears }), shallow)325```326327### Multiple Stores328329You can create more than one store for different domains. For example, `BearStore` manages bears and `FishStore` manages fish.330This keeps state isolated and easier to maintain in larger apps. With TypeScript, each store has its own strict type - you can’t accidentally mix bears and fish.331332```tsx333import { create } from 'zustand'334335// Bear store with explicit types336interface BearState {337 bears: number338 addBear: () => void339}340341const useBearStore = create<BearState>()((set) => ({342 bears: 2,343 addBear: () => set((s) => ({ bears: s.bears + 1 })),344}))345346// Fish store with explicit types347interface FishState {348 fish: number349 addFish: () => void350}351352const useFishStore = create<FishState>()((set) => ({353 fish: 5,354 addFish: () => set((s) => ({ fish: s.fish + 1 })),355}))356357// In components, you can use both stores safely358function Zoo() {359 const { bears, addBear } = useBearStore()360 const { fish, addFish } = useFishStore()361362 return (363 <div>364 <div>365 {bears} bears and {fish} fish366 </div>367 <button onClick={addBear}>Add bear</button>368 <button onClick={addFish}>Add fish</button>369 </div>370 )371}372```373374### Conclusion375376Zustand together with TypeScript provides a balance: you keep the simplicity of small, minimalistic stores, while gaining the safety of strong typing.377You don’t need boilerplate or complex patterns - state and actions live side by side, fully typed, and ready to use.378Start with a basic store to learn the pattern, then expand gradually: use `combine` for cleaner inference, `persist` for storage, and `devtools` for debugging.
added:docs/learn/guides/connect-to-state-with-url-hash.md+153 added
1---2title: Connect to state with URL3nav: 104---56## Connect State with URL Hash78If you want to connect state of a store to URL hash, you can create your own hash storage.910```ts11import { create } from 'zustand'12import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'1314const hashStorage: StateStorage = {15 getItem: (key): string => {16 const searchParams = new URLSearchParams(location.hash.slice(1))17 const storedValue = searchParams.get(key) ?? ''18 return JSON.parse(storedValue)19 },20 setItem: (key, newValue): void => {21 const searchParams = new URLSearchParams(location.hash.slice(1))22 searchParams.set(key, JSON.stringify(newValue))23 location.hash = searchParams.toString()24 },25 removeItem: (key): void => {26 const searchParams = new URLSearchParams(location.hash.slice(1))27 searchParams.delete(key)28 location.hash = searchParams.toString()29 },30}3132export const useBoundStore = create()(33 persist(34 (set, get) => ({35 fishes: 0,36 addAFish: () => set({ fishes: get().fishes + 1 }),37 }),38 {39 name: 'food-storage', // unique name40 storage: createJSONStorage(() => hashStorage),41 },42 ),43)44```4546## Persist and Connect State with URL Parameters (Example: URL Query Parameters)4748There are times when you want to conditionally connect the state to the URL.49This example depicts usage of the URL query parameters50while keeping it synced with another persistence implementation, like `localstorage`.5152If you want the URL params to always populate, the conditional check on `getUrlSearch()` can be removed.5354The implementation below will update the URL in place, without refresh, as the relevant states change.5556```ts57import { create } from 'zustand'58import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'5960const getUrlSearch = () => {61 return window.location.search.slice(1)62}6364const persistentStorage: StateStorage = {65 getItem: (key): string => {66 // Check URL first67 if (getUrlSearch()) {68 const searchParams = new URLSearchParams(getUrlSearch())69 const storedValue = searchParams.get(key)70 return JSON.parse(storedValue as string)71 } else {72 // Otherwise, we should load from localstorage or alternative storage73 return JSON.parse(localStorage.getItem(key) as string)74 }75 },76 setItem: (key, newValue): void => {77 // Check if query params exist at all, can remove check if always want to set URL78 if (getUrlSearch()) {79 const searchParams = new URLSearchParams(getUrlSearch())80 searchParams.set(key, JSON.stringify(newValue))81 window.history.replaceState(null, '', `?${searchParams.toString()}`)82 }8384 localStorage.setItem(key, JSON.stringify(newValue))85 },86 removeItem: (key): void => {87 const searchParams = new URLSearchParams(getUrlSearch())88 searchParams.delete(key)89 window.location.search = searchParams.toString()90 },91}9293type LocalAndUrlStore = {94 typesOfFish: string[]95 addTypeOfFish: (fishType: string) => void96 numberOfBears: number97 setNumberOfBears: (newNumber: number) => void98}99100const storageOptions = {101 name: 'fishAndBearsStore',102 storage: createJSONStorage<LocalAndUrlStore>(() => persistentStorage),103}104105const useLocalAndUrlStore = create()(106 persist<LocalAndUrlStore>(107 (set) => ({108 typesOfFish: [],109 addTypeOfFish: (fishType) =>110 set((state) => ({ typesOfFish: [...state.typesOfFish, fishType] })),111112 numberOfBears: 0,113 setNumberOfBears: (numberOfBears) => set(() => ({ numberOfBears })),114 }),115 storageOptions,116 ),117)118119export default useLocalAndUrlStore120```121122When generating the URL from a component, you can call buildShareableUrl:123124```ts125const buildURLSuffix = (params, version = 0) => {126 const searchParams = new URLSearchParams()127128 const zustandStoreParams = {129 state: {130 typesOfFish: params.typesOfFish,131 numberOfBears: params.numberOfBears,132 },133 version: version, // version is here because that is included with how Zustand sets the state134 }135136 // The URL param key should match the name of the store, as specified as in storageOptions above137 searchParams.set('fishAndBearsStore', JSON.stringify(zustandStoreParams))138 return searchParams.toString()139}140141export const buildShareableUrl = (params, version) => {142 return `${window.location.origin}?${buildURLSuffix(params, version)}`143}144```145146The generated URL would look like (here without any encoding, for readability):147148`https://localhost/search?fishAndBearsStore={"state":{"typesOfFish":["tilapia","salmon"],"numberOfBears":15},"version":0}}`149150### Demo151152- Hash: https://stackblitz.com/edit/vitejs-vite-9vg24prg153- Query: https://stackblitz.com/edit/vitejs-vite-hyc97ynf
added:docs/learn/guides/event-handler-in-pre-react-18.md+24 added
1---2title: Calling actions outside a React event handler in pre React 183nav: 114---56Because React handles `setState` synchronously if it's called outside an event handler, updating the state outside an event handler will force react to update the components synchronously. Therefore, there is a risk of encountering the zombie-child effect.7In order to fix this, the action needs to be wrapped in `unstable_batchedUpdates` like so:89```jsx10import { unstable_batchedUpdates } from 'react-dom' // or 'react-native'1112const useFishStore = create((set) => ({13 fishes: 0,14 increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 })),15}))1617const nonReactCallback = () => {18 unstable_batchedUpdates(() => {19 useFishStore.getState().increaseFishes()20 })21}22```2324More details: https://github.com/pmndrs/zustand/issues/302
added:docs/learn/guides/flux-inspired-practice.md+77 added
1---2title: Flux inspired practice3nav: 194---56Although Zustand is an unopinionated library, we do recommend a few patterns.7These are inspired by practices originally found in [Flux](https://github.com/facebookarchive/flux),8and more recently [Redux](https://redux.js.org/understanding/thinking-in-redux/three-principles),9so if you are coming from another library, you should feel right at home.1011However, Zustand does differ in some fundamental ways,12so some terminology may not perfectly align to other libraries.1314## Recommended patterns1516### Single store1718Your applications global state should be located in a single Zustand store.1920If you have a large application, Zustand supports [splitting the store into slices](./slices-pattern.md).2122### Use `set` / `setState` to update the store2324Always use `set` (or `setState`) to perform updates to your store.25`set` (and `setState`) ensures the described update is correctly merged and listeners are appropriately notified.2627### Colocate store actions2829In Zustand, state can be updated without the use of dispatched actions and reducers found in other Flux libraries.30These store actions can be added directly to the store as shown below.3132Optionally, by using `setState` they can be [located external to the store](./practice-with-no-store-actions.md)3334```js35const useBoundStore = create((set) => ({36 storeSliceA: ...,37 storeSliceB: ...,38 storeSliceC: ...,39 updateX: () => set(...),40 updateY: () => set(...),41}))42```4344## Redux-like patterns4546If you can't live without Redux-like reducers, you can define a `dispatch` function on the root level of the store:4748```typescript49const types = { increase: 'INCREASE', decrease: 'DECREASE' }5051const reducer = (state, { type, by = 1 }) => {52 switch (type) {53 case types.increase:54 return { grumpiness: state.grumpiness + by }55 case types.decrease:56 return { grumpiness: state.grumpiness - by }57 }58}5960const useGrumpyStore = create((set) => ({61 grumpiness: 0,62 dispatch: (args) => set((state) => reducer(state, args)),63}))6465const dispatch = useGrumpyStore((state) => state.dispatch)66dispatch({ type: types.increase, by: 2 })67```6869You could also use our redux-middleware. It wires up your main reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api.7071```typescript72import { redux } from 'zustand/middleware'7374const useReduxStore = create(redux(reducer, initialState))75```7677Another way to update the store could be through functions wrapping the state functions. These could also handle side-effects of actions. For example, with HTTP-calls. To use Zustand in a non-reactive way, see [the readme](https://github.com/pmndrs/zustand#readingwriting-state-and-reacting-to-changes-outside-of-components).
added:docs/learn/guides/how-to-reset-state.md+45 added
1---2title: How to reset state3nav: 204---56The following pattern can be used to reset the state to its initial value.78```ts9const useSomeStore = create<State & Actions>()((set, get, store) => ({10 // your code here11 reset: () => {12 set(store.getInitialState())13 },14}))15```1617Resetting multiple stores at once1819```ts20import type { StateCreator } from 'zustand'21import { create: actualCreate } from 'zustand'2223const storeResetFns = new Set<() => void>()2425const resetAllStores = () => {26 storeResetFns.forEach((resetFn) => {27 resetFn()28 })29}3031export const create = (<T>() => {32 return (stateCreator: StateCreator<T>) => {33 const store = actualCreate(stateCreator)34 storeResetFns.add(() => {35 store.setState(store.getInitialState(), true)36 })37 return store38 }39}) as typeof actualCreate40```4142## Demo4344- Basic: https://stackblitz.com/edit/zustand-how-to-reset-state-basic45- Advanced: https://stackblitz.com/edit/zustand-how-to-reset-state-advanced
added:docs/learn/guides/immutable-state-and-merging.md+59 added
1---2title: Immutable state and merging3nav: 74---56Like with React's `useState`, we need to update state immutably.78Here's a typical example:910```jsx11import { create } from 'zustand'1213const useCountStore = create((set) => ({14 count: 0,15 inc: () => set((state) => ({ count: state.count + 1 })),16}))17```1819The `set` function is to update state in the store.20Because the state is immutable, it should have been like this:2122```js23set((state) => ({ ...state, count: state.count + 1 }))24```2526However, as this is a common pattern, `set` actually merges state, and27we can skip the `...state` part:2829```js30set((state) => ({ count: state.count + 1 }))31```3233## Nested objects3435The `set` function merges state at only one level.36If you have a nested object, you need to merge them explicitly. You will use the spread operator pattern like so:3738```jsx39import { create } from 'zustand'4041const useCountStore = create((set) => ({42 nested: { count: 0 },43 inc: () =>44 set((state) => ({45 nested: { ...state.nested, count: state.nested.count + 1 },46 })),47}))48```4950For complex use cases, consider using some libraries that help with immutable updates.51You can refer to [Updating nested state object values](./updating-state.md#deeply-nested-object).5253## Replace flag5455To disable the merging behavior, you can specify a `replace` boolean value for `set` like so:5657```js58set((state) => newState, true)59```
added:docs/learn/guides/initialize-state-with-props.md+180 added
1---2title: Initialize state with props3nav: 174---56In cases where [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) is needed, such as when a store should be initialized with props from a component, the recommended approach is to use a vanilla store with React.context.78## Store creator with `createStore`910```ts11import { createStore } from 'zustand'1213interface BearProps {14 bears: number15}1617interface BearState extends BearProps {18 addBear: () => void19}2021type BearStore = ReturnType<typeof createBearStore>2223const createBearStore = (initProps?: Partial<BearProps>) => {24 const DEFAULT_PROPS: BearProps = {25 bears: 0,26 }27 return createStore<BearState>()((set) => ({28 ...DEFAULT_PROPS,29 ...initProps,30 addBear: () => set((state) => ({ bears: ++state.bears })),31 }))32}33```3435## Creating a context with `React.createContext`3637```ts38import { createContext } from 'react'3940export const BearContext = createContext<BearStore | null>(null)41```4243## Basic component usage4445```tsx46// Provider implementation47import { useState } from 'react'4849function App() {50 const [store] = useState(() => createBearStore())51 return (52 <BearContext.Provider value={store}>53 <BasicConsumer />54 </BearContext.Provider>55 )56}57```5859```tsx60// Consumer component61import { useContext } from 'react'62import { useStore } from 'zustand'6364function BasicConsumer() {65 const store = useContext(BearContext)66 if (!store) throw new Error('Missing BearContext.Provider in the tree')6768 const bears = useStore(store, (s) => s.bears)69 const addBear = useStore(store, (s) => s.addBear)7071 return (72 <>73 <div>{bears} Bears.</div>74 <button onClick={addBear}>Add bear</button>75 </>76 )77}78```7980## Common patterns8182### Wrapping the context provider8384```tsx85// Provider wrapper86import { useState } from 'react'8788type BearProviderProps = React.PropsWithChildren<BearProps>8990function BearProvider({ children, ...props }: BearProviderProps) {91 const [store] = useState(() => createBearStore(props))92 return <BearContext.Provider value={store}>{children}</BearContext.Provider>93}94```9596### Extracting context logic into a custom hook9798```tsx99// Mimic the hook returned by `create`100import { useContext } from 'react'101import { useStore } from 'zustand'102103function useBearContext<T>(selector: (state: BearState) => T): T {104 const store = useContext(BearContext)105 if (!store) throw new Error('Missing BearContext.Provider in the tree')106 return useStore(store, selector)107}108```109110```tsx111// Consumer usage of the custom hook112function CommonConsumer() {113 const bears = useBearContext((s) => s.bears)114 const addBear = useBearContext((s) => s.addBear)115 return (116 <>117 <div>{bears} Bears.</div>118 <button onClick={addBear}>Add bear</button>119 </>120 )121}122```123124### Optionally use memoized selector for stable outputs125126```tsx127import { useShallow } from 'zustand/react/shallow'128129const meals = ['Salmon', 'Berries', 'Nuts']130131function CommonConsumer() {132 const bearMealsOrder = useBearContext(133 useShallow((s) =>134 Array.from({ length: s.bears }).map((_, index) =>135 meals.at(index % meals.length),136 ),137 ),138 )139 return (140 <>141 Order:142 <ul>143 {bearMealsOrder.map((meal) => (144 <li key={meal}>{meal}</li>145 ))}146 </ul>147 </>148 )149}150```151152### Optionally allow using a custom equality function153154```tsx155// Allow custom equality function by using useStoreWithEqualityFn instead of useStore156import { useContext } from 'react'157import { useStoreWithEqualityFn } from 'zustand/traditional'158159function useBearContext<T>(160 selector: (state: BearState) => T,161 equalityFn?: (left: T, right: T) => boolean,162): T {163 const store = useContext(BearContext)164 if (!store) throw new Error('Missing BearContext.Provider in the tree')165 return useStoreWithEqualityFn(store, selector, equalityFn)166}167```168169### Complete example170171```tsx172// Provider wrapper & custom hook consumer173function App2() {174 return (175 <BearProvider bears={2}>176 <HookConsumer />177 </BearProvider>178 )179}180```
added:docs/learn/guides/maps-and-sets-usage.md+115 added
1---2title: Map and Set Usage3nav: 84---56# Map and Set in Zustand78Map and Set are mutable data structures. To use them in Zustand, you must create new instances when updating.910## Map1112### Reading a Map1314```typescript15const foo = useSomeStore((state) => state.foo)16```1718### Updating a Map1920Always create a new Map instance:2122```ts23// Update single entry24set((state) => ({25 foo: new Map(state.foo).set(key, value),26}))2728// Delete entry29set((state) => {30 const next = new Map(state.foo)31 next.delete(key)32 return { foo: next }33})3435// Update multiple entries36set((state) => {37 const next = new Map(state.foo)38 next.set('key1', 'value1')39 next.set('key2', 'value2')40 return { foo: next }41})4243// Clear44set({ foo: new Map() })45```4647## Set4849### Reading a Set5051```ts52const bar = useSomeStore((state) => state.bar)53```5455### Updating a Set5657Always create a new Set instance:5859```ts60// Add item61set((state) => ({62 bar: new Set(state.bar).add(item),63}))6465// Delete item66set((state) => {67 const next = new Set(state.bar)68 next.delete(item)69 return { bar: next }70})7172// Toggle item73set((state) => {74 const next = new Set(state.bar)75 next.has(item) ? next.delete(item) : next.add(item)76 return { bar: next }77})7879// Clear80set({ bar: new Set() })81```8283## Why New Instances?8485Zustand detects changes by comparing references. Mutating a Map or Set doesn't change its reference:8687```ts88// ❌ Wrong - same reference, no re-render89set((state) => {90 state.foo.set(key, value)91 return { foo: state.foo }92})9394// ✅ Correct - new reference, triggers re-render95set((state) => ({96 foo: new Map(state.foo).set(key, value),97}))98```99100## Pitfall: Type Hints for Empty Collections101102Provide type hints when initializing empty Maps and Sets:103104```ts105{106 ids: new Set([] as string[]),107 users: new Map([] as [string, User][])108}109```110111Without type hints, TypeScript infers `never[]` which prevents adding items later.112113## Demos114115Basic: https://stackblitz.com/edit/vitejs-vite-5cu5ddvx
added:docs/learn/guides/nextjs.md+316 added
1---2title: Setup with Next.js3nav: 154---56> [!NOTE]7> We will be updating this guide soon based on our discussion in https://github.com/pmndrs/zustand/discussions/2740.89[Next.js](https://nextjs.org) is a popular server-side rendering framework for React that presents10some unique challenges for using Zustand properly.11Keep in mind that Zustand store is a global12variable (AKA module state) making it optional to use a `Context`.13These challenges include:1415- **Per-request store:** A Next.js server can handle multiple requests simultaneously. This means16 that the store should be created per request and should not be shared across requests.17- **SSR friendly:** Next.js applications are rendered twice, first on the server18 and again on the client. Having different outputs on both the client and the server will result19 in "hydration errors." The store will have to be initialized on the server and then20 re-initialized on the client with the same data in order to avoid that. Please read more about21 that in our [SSR and Hydration](./ssr-and-hydration.md) guide.22- **SPA routing friendly:** Next.js supports a hybrid model for client side routing, which means23 that in order to reset a store, we need to initialize it at the component level using a24 `Context`.25- **Server caching friendly:** Recent versions of Next.js (specifically applications using the App26 Router architecture) support aggressive server caching. Due to our store being a **module state**,27 it is completely compatible with this caching.2829We have these general recommendations for the appropriate use of Zustand:3031- **No global stores** - Because the store should not be shared across requests, it should not be defined32 as a global variable. Instead, the store should be created per request.33- **React Server Components should not read from or write to the store** - RSCs cannot use hooks or context. They aren't34 meant to be stateful. Having an RSC read from or write values to a global store violates the35 architecture of Next.js.3637### Creating a store per request3839Let's write our store factory function that will create a new store for each40request.4142```json43// tsconfig.json44{45 "compilerOptions": {46 "lib": ["dom", "dom.iterable", "esnext"],47 "allowJs": true,48 "skipLibCheck": true,49 "strict": true,50 "noEmit": true,51 "esModuleInterop": true,52 "module": "esnext",53 "moduleResolution": "bundler",54 "resolveJsonModule": true,55 "isolatedModules": true,56 "jsx": "preserve",57 "incremental": true,58 "plugins": [59 {60 "name": "next"61 }62 ],63 "paths": {64 "@/*": ["./src/*"]65 }66 },67 "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],68 "exclude": ["node_modules"]69}70```7172> **Note:** do not forget to remove all comments from your `tsconfig.json` file.7374### Initializing the store7576```ts77// src/stores/counter-store.ts78import { createStore } from 'zustand/vanilla'7980export type CounterState = {81 count: number82}8384export type CounterActions = {85 decrementCount: () => void86 incrementCount: () => void87}8889export type CounterStore = CounterState & CounterActions9091export const defaultInitState: CounterState = {92 count: 0,93}9495export const createCounterStore = (96 initState: CounterState = defaultInitState,97) => {98 return createStore<CounterStore>()((set) => ({99 ...initState,100 decrementCount: () => set((state) => ({ count: state.count - 1 })),101 incrementCount: () => set((state) => ({ count: state.count + 1 })),102 }))103}104```105106### Providing the store107108Let's use the `createCounterStore` in our component and share it using a context provider.109110```tsx111// src/providers/counter-store-provider.tsx112'use client'113114import { type ReactNode, createContext, useState, useContext } from 'react'115import { useStore } from 'zustand'116117import { type CounterStore, createCounterStore } from '@/stores/counter-store'118119export type CounterStoreApi = ReturnType<typeof createCounterStore>120121export const CounterStoreContext = createContext<CounterStoreApi | undefined>(122 undefined,123)124125export interface CounterStoreProviderProps {126 children: ReactNode127}128129export const CounterStoreProvider = ({130 children,131}: CounterStoreProviderProps) => {132 const [store] = useState(() => createCounterStore())133 return (134 <CounterStoreContext.Provider value={store}>135 {children}136 </CounterStoreContext.Provider>137 )138}139140export const useCounterStore = <T,>(141 selector: (store: CounterStore) => T,142): T => {143 const counterStoreContext = useContext(CounterStoreContext)144 if (!counterStoreContext) {145 throw new Error(`useCounterStore must be used within CounterStoreProvider`)146 }147148 return useStore(counterStoreContext, selector)149}150```151152> **Note:** In this example, we ensure that this component is re-render-safe by checking the153> value of the reference, so that the store is only created once. This component will only be154> rendered once per request on the server, but might be re-rendered multiple times on the client if155> there are stateful client components located above this component in the tree, or if this component156> also contains other mutable state that causes a re-render.157158### Using the store with different architectures159160There are two architectures for a Next.js application: the161[Pages Router](https://nextjs.org/docs/pages/building-your-application/routing) and the162[App Router](https://nextjs.org/docs/app/building-your-application/routing). The usage of Zustand on163both architectures should be the same with slight differences related to each architecture.164165#### Pages Router166167```tsx168// src/components/pages/home-page.tsx169import { useCounterStore } from '@/providers/counter-store-provider'170171export const HomePage = () => {172 const { count, incrementCount, decrementCount } = useCounterStore(173 (state) => state,174 )175176 return (177 <div>178 Count: {count}179 <hr />180 <button type="button" onClick={incrementCount}>181 Increment Count182 </button>183 <button type="button" onClick={decrementCount}>184 Decrement Count185 </button>186 </div>187 )188}189```190191```tsx192// src/_app.tsx193import type { AppProps } from 'next/app'194195import { CounterStoreProvider } from '@/providers/counter-store-provider'196197export default function App({ Component, pageProps }: AppProps) {198 return (199 <CounterStoreProvider>200 <Component {...pageProps} />201 </CounterStoreProvider>202 )203}204```205206```tsx207// src/pages/index.tsx208import { HomePage } from '@/components/pages/home-page'209210export default function Home() {211 return <HomePage />212}213```214215> **Note:** creating a store per route would require creating and sharing the store216> at page (route) component level. Try not to use this if you do not need to create217> a store per route.218219```tsx220// src/pages/index.tsx221import { CounterStoreProvider } from '@/providers/counter-store-provider'222import { HomePage } from '@/components/pages/home-page'223224export default function Home() {225 return (226 <CounterStoreProvider>227 <HomePage />228 </CounterStoreProvider>229 )230}231```232233#### App Router234235```tsx236// src/components/pages/home-page.tsx237'use client'238239import { useCounterStore } from '@/providers/counter-store-provider'240241export const HomePage = () => {242 const { count, incrementCount, decrementCount } = useCounterStore(243 (state) => state,244 )245246 return (247 <div>248 Count: {count}249 <hr />250 <button type="button" onClick={incrementCount}>251 Increment Count252 </button>253 <button type="button" onClick={decrementCount}>254 Decrement Count255 </button>256 </div>257 )258}259```260261```tsx262// src/app/layout.tsx263import type { Metadata } from 'next'264import { Inter } from 'next/font/google'265import './globals.css'266267import { CounterStoreProvider } from '@/providers/counter-store-provider'268269const inter = Inter({ subsets: ['latin'] })270271export const metadata: Metadata = {272 title: 'Create Next App',273 description: 'Generated by create next app',274}275276export default function RootLayout({277 children,278}: Readonly<{279 children: React.ReactNode280}>) {281 return (282 <html lang="en">283 <body className={inter.className}>284 <CounterStoreProvider>{children}</CounterStoreProvider>285 </body>286 </html>287 )288}289```290291```tsx292// src/app/page.tsx293import { HomePage } from '@/components/pages/home-page'294295export default function Home() {296 return <HomePage />297}298```299300> **Note:** creating a store per route would require creating and sharing the store301> at page (route) component level. Try not to use this if you do not need to create302> a store per route.303304```tsx305// src/app/page.tsx306import { CounterStoreProvider } from '@/providers/counter-store-provider'307import { HomePage } from '@/components/pages/home-page'308309export default function Home() {310 return (311 <CounterStoreProvider>312 <HomePage />313 </CounterStoreProvider>314 )315}316```
added:docs/learn/guides/practice-with-no-store-actions.md+42 added
1---2title: Practice with no store actions3nav: 54---56The recommended usage is to colocate actions and states within the store (let your actions be located together with your state).78For example:910```js11export const useBoundStore = create((set) => ({12 count: 0,13 text: 'hello',14 inc: () => set((state) => ({ count: state.count + 1 })),15 setText: (text) => set({ text }),16}))17```1819This creates a self-contained store with data and actions together.2021---2223An alternative approach is to define actions at module level, external to the store.2425```js26export const useBoundStore = create(() => ({27 count: 0,28 text: 'hello',29}))3031export const inc = () =>32 useBoundStore.setState((state) => ({ count: state.count + 1 }))3334export const setText = (text) => useBoundStore.setState({ text })35```3637This has a few advantages:3839- It doesn't require a hook to call an action;40- It facilitates code splitting.4142While this pattern doesn't offer any downsides, some may prefer colocating due to its encapsulated nature.
added:docs/learn/guides/prevent-rerenders-with-use-shallow.md+63 added
1---2title: Prevent rerenders with useShallow3nav: 94---56When you need to subscribe to a computed state from a store, the recommended way is to7use a selector.89The computed selector will cause a rerender if the output has changed according to [Object.is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is?retiredLocale=it).1011In this case you might want to use `useShallow` to avoid a rerender if the computed value is always shallow12equal the previous one.1314## Example1516We have a store that associates to each bear a meal and we want to render their names.1718```js19import { create } from 'zustand'2021const useMeals = create(() => ({22 papaBear: 'large porridge-pot',23 mamaBear: 'middle-size porridge pot',24 littleBear: 'A little, small, wee pot',25}))2627export const BearNames = () => {28 const names = useMeals((state) => Object.keys(state))2930 return <div>{names.join(', ')}</div>31}32```3334Now papa bear wants a pizza instead:3536```js37useMeals.setState({38 papaBear: 'a large pizza',39})40```4142This change causes `BearNames` rerenders even though the actual output of `names` has not changed according to shallow equal.4344We can fix that using `useShallow`!4546```js47import { create } from 'zustand'48import { useShallow } from 'zustand/react/shallow'4950const useMeals = create(() => ({51 papaBear: 'large porridge-pot',52 mamaBear: 'middle-size porridge pot',53 littleBear: 'A little, small, wee pot',54}))5556export const BearNames = () => {57 const names = useMeals(useShallow((state) => Object.keys(state)))5859 return <div>{names.join(', ')}</div>60}61```6263Now they can all order other meals without causing unnecessary rerenders of our `BearNames` component.
added:docs/learn/guides/slices-pattern.md+120 added
1---2title: Slices Pattern3nav: 64---56## Slicing the store into smaller stores78Your store can become bigger and bigger and tougher to maintain as you add more features.910You can divide your main store into smaller individual stores to achieve modularity. This is simple to accomplish in Zustand!1112The first individual store:1314```js15export const createFishSlice = (set) => ({16 fishes: 0,17 addFish: () => set((state) => ({ fishes: state.fishes + 1 })),18})19```2021Another individual store:2223```js24export const createBearSlice = (set) => ({25 bears: 0,26 addBear: () => set((state) => ({ bears: state.bears + 1 })),27 eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),28})29```3031You can now combine both the stores into **one bounded store**:3233```js34import { create } from 'zustand'35import { createBearSlice } from './bearSlice'36import { createFishSlice } from './fishSlice'3738export const useBoundStore = create((...a) => ({39 ...createBearSlice(...a),40 ...createFishSlice(...a),41}))42```4344### Usage in a React component4546```jsx47import { useBoundStore } from './stores/useBoundStore'4849function App() {50 const bears = useBoundStore((state) => state.bears)51 const fishes = useBoundStore((state) => state.fishes)52 const addBear = useBoundStore((state) => state.addBear)53 return (54 <div>55 <h2>Number of bears: {bears}</h2>56 <h2>Number of fishes: {fishes}</h2>57 <button onClick={() => addBear()}>Add a bear</button>58 </div>59 )60}6162export default App63```6465### Updating multiple stores6667You can update multiple stores, at the same time, in a single function.6869```js70export const createBearFishSlice = (set, get) => ({71 addBearAndFish: () => {72 get().addBear()73 get().addFish()74 },75})76```7778Combining all the stores together is the same as before.7980```js81import { create } from 'zustand'82import { createBearSlice } from './bearSlice'83import { createFishSlice } from './fishSlice'84import { createBearFishSlice } from './createBearFishSlice'8586export const useBoundStore = create((...a) => ({87 ...createBearSlice(...a),88 ...createFishSlice(...a),89 ...createBearFishSlice(...a),90}))91```9293## Adding middlewares9495Adding middlewares to a combined store is the same as with other normal stores.9697Adding [`persist` middleware](../../reference/integrations/persisting-store-data.md) to our `useBoundStore`:9899```js100import { create } from 'zustand'101import { createBearSlice } from './bearSlice'102import { createFishSlice } from './fishSlice'103import { persist } from 'zustand/middleware'104105export const useBoundStore = create(106 persist(107 (...a) => ({108 ...createBearSlice(...a),109 ...createFishSlice(...a),110 }),111 { name: 'bound-store' },112 ),113)114```115116Please keep in mind you should only apply middlewares in the combined store. Applying them inside individual slices can lead to unexpected issues.117118## Usage with TypeScript119120A detailed guide on how to use the slice pattern in Zustand with TypeScript can be found [here](./advanced-typescript.md#slices-pattern).
added:docs/learn/guides/ssr-and-hydration.md+198 added
1---2title: SSR and Hydration3nav: 164---56## Server-side Rendering (SSR)78Server-side Rendering (SSR) is a technique that helps us render our components into9HTML strings on the server, send them directly to the browser, and finally "hydrate" the10static markup into a fully interactive app on the client.1112### React1314Let's say we want to render a stateless app using React. In order to do that, we need15to use `express`, `react` and `react-dom/server`. We don't need `react-dom/client`16since it's a stateless app.1718Let's dive into that:1920- `express` helps us build a web app that we can run using Node,21- `react` helps us build the UI components that we use in our app,22- `react-dom/server` helps us render our components on a server.2324```json25// tsconfig.json26{27 "compilerOptions": {28 "noImplicitAny": false,29 "noEmitOnError": true,30 "removeComments": false,31 "sourceMap": true,32 "target": "esnext"33 },34 "include": ["**/*"]35}36```3738> **Note:** do not forget to remove all comments from your `tsconfig.json` file.3940```tsx41// app.tsx42export const App = () => {43 return (44 <html>45 <head>46 <meta charSet="utf-8" />47 <meta name="viewport" content="width=device-width, initial-scale=1" />48 <title>Static Server-side-rendered App</title>49 </head>50 <body>51 <div>Hello World!</div>52 </body>53 </html>54 )55}56```5758```tsx59// server.tsx60import express from 'express'61import React from 'react'62import ReactDOMServer from 'react-dom/server'6364import { App } from './app.tsx'6566const port = Number.parseInt(process.env.PORT || '3000', 10)67const app = express()6869app.get('/', (_, res) => {70 const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {71 onShellReady() {72 res.setHeader('content-type', 'text/html')73 pipe(res)74 },75 })76})7778app.listen(port, () => {79 console.log(`Server is listening at ${port}`)80})81```8283```sh84tsc --build85```8687```sh88node server.js89```9091## Hydration9293Hydration turns the initial HTML snapshot from the server into a fully interactive app94that runs in the browser. The right way to "hydrate" a component is by using `hydrateRoot`.9596### React9798Let's say we want to render a stateful app using React. In order to do that we need to99use `express`, `react`, `react-dom/server` and `react-dom/client`.100101Let's dive into that:102103- `express` helps us build a web app that we can run using Node,104- `react` helps us build the UI components that we use in our app,105- `react-dom/server` helps us render our components on a server,106- `react-dom/client` helps us hydrate our components on a client.107108> **Note:** Do not forget that even if we can render our components on a server, it is109> important to "hydrate" them on a client to make them interactive.110111```json112// tsconfig.json113{114 "compilerOptions": {115 "noImplicitAny": false,116 "noEmitOnError": true,117 "removeComments": false,118 "sourceMap": true,119 "target": "esnext"120 },121 "include": ["**/*"]122}123```124125> **Note:** do not forget to remove all comments in your `tsconfig.json` file.126127```tsx128// app.tsx129export const App = () => {130 return (131 <html>132 <head>133 <meta charSet="utf-8" />134 <meta name="viewport" content="width=device-width, initial-scale=1" />135 <title>Static Server-side-rendered App</title>136 </head>137 <body>138 <div>Hello World!</div>139 </body>140 </html>141 )142}143```144145```tsx146// main.tsx147import ReactDOMClient from 'react-dom/client'148149import { App } from './app.tsx'150151ReactDOMClient.hydrateRoot(document, <App />)152```153154```tsx155// server.tsx156import express from 'express'157import React from 'react'158import ReactDOMServer from 'react-dom/server'159160import { App } from './app.tsx'161162const port = Number.parseInt(process.env.PORT || '3000', 10)163const app = express()164165app.use('/', (_, res) => {166 const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {167 bootstrapScripts: ['/main.js'],168 onShellReady() {169 res.setHeader('content-type', 'text/html')170 pipe(res)171 },172 })173})174175app.listen(port, () => {176 console.log(`Server is listening at ${port}`)177})178```179180```sh181tsc --build182```183184```sh185node server.js186```187188> **Warning:** The React tree you pass to `hydrateRoot` needs to produce the same output as it did on the server.189> The most common causes leading to hydration errors include:190>191> - Extra whitespace (like newlines) around the React-generated HTML inside the root node.192> - Using checks like typeof window !== 'undefined' in your rendering logic.193> - Using browser-only APIs like `window.matchMedia` in your rendering logic.194> - Rendering different data on the server and the client.195>196> React recovers from some hydration errors, but you must fix them like other bugs. In the best case, they’ll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.197198You can read more about the caveats and pitfalls here: [hydrateRoot](https://react.dev/reference/react-dom/client/hydrateRoot)
added:docs/learn/guides/testing.md+741 added
1---2title: Testing3description: Writing Tests4nav: 185---67## Setting Up a Test Environment89### Test Runners1011Usually, your test runner needs to be configured to run JavaScript/TypeScript syntax. If you're12going to be testing UI components, you will likely need to configure the test runner to use JSDOM13to provide a mock DOM environment.1415See these resources for test runner configuration instructions:1617- **Jest**18 - [Jest: Getting Started](https://jestjs.io/docs/getting-started)19 - [Jest: Configuration - Test Environment](https://jestjs.io/docs/configuration#testenvironment-string)20- **Vitest**21 - [Vitest: Getting Started](https://vitest.dev/guide)22 - [Vitest: Configuration - Test Environment](https://vitest.dev/config/#environment)2324### UI and Network Testing Tools2526**We recommend using [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)27to test out React components that connect to Zustand**. RTL is a simple and complete React DOM28testing utility that encourages good testing practices. It uses ReactDOM's `render` function and29`act` from `react-dom/tests-utils`. Furthermore, [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)30is the alternative to RTL to test out React Native components. The [Testing Library](https://testing-library.com/)31family of tools also includes adapters for many other popular frameworks.3233We also recommend using [Mock Service Worker (MSW)](https://mswjs.io/) to mock network requests, as34this means your application logic does not need to be changed or mocked when writing tests.3536- **React Testing Library (DOM)**37 - [DOM Testing Library: Setup](https://testing-library.com/docs/dom-testing-library/setup)38 - [React Testing Library: Setup](https://testing-library.com/docs/react-testing-library/setup)39 - [Testing Library Jest-DOM Matchers](https://testing-library.com/docs/ecosystem-jest-dom)40- **Native Testing Library (React Native)**41 - [Native Testing Library: Setup](https://testing-library.com/docs/react-native-testing-library/setup)42- **User Event Testing Library (DOM)**43 - [User Event Testing Library: Setup](https://testing-library.com/docs/user-event/setup)44- **TypeScript for Jest**45 - [TypeScript for Jest: Setup](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation)46- **TypeScript for Node**47 - [TypeScript for Node: Setup](https://typestrong.org/ts-node/docs/installation)48- **Mock Service Worker**49 - [MSW: Installation](https://mswjs.io/docs/getting-started/install)50 - [MSW: Setting up mock requests](https://mswjs.io/docs/getting-started/mocks/rest-api)51 - [MSW: Mock server configuration for Node](https://mswjs.io/docs/getting-started/integrate/node)5253## Setting Up Zustand for testing5455> **Note**: Since Jest and Vitest have slight differences, like Vitest using **ES modules** and Jest using56> **CommonJS modules**, you need to keep that in mind if you are using Vitest instead of Jest.5758The mock provided below will enable the relevant test runner to reset the zustand stores after each test.5960### Shared code just for testing purposes6162This shared code was added to avoid code duplication in our demo since we use the same counter store63creator for both implementations, with and without `Context` API — `createStore` and `create`, respectively.6465```ts66// shared/counter-store-creator.ts67import { type StateCreator } from 'zustand'6869export type CounterStore = {70 count: number71 inc: () => void72}7374export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({75 count: 1,76 inc: () => set((state) => ({ count: state.count + 1 })),77})78```7980### Jest8182In the next steps we are going to setup our Jest environment in order to mock Zustand.8384```ts85// __mocks__/zustand.ts86import { act } from '@testing-library/react'87import type * as ZustandExportedTypes from 'zustand'88export * from 'zustand'8990const { create: actualCreate, createStore: actualCreateStore } =91 jest.requireActual<typeof ZustandExportedTypes>('zustand')9293// a variable to hold reset functions for all stores declared in the app94export const storeResetFns = new Set<() => void>()9596const createUncurried = <T>(97 stateCreator: ZustandExportedTypes.StateCreator<T>,98) => {99 const store = actualCreate(stateCreator)100 const initialState = store.getInitialState()101 storeResetFns.add(() => {102 store.setState(initialState, true)103 })104 return store105}106107// when creating a store, we get its initial state, create a reset function and add it in the set108export const create = (<T>(109 stateCreator: ZustandExportedTypes.StateCreator<T>,110) => {111 console.log('zustand create mock')112113 // to support curried version of create114 return typeof stateCreator === 'function'115 ? createUncurried(stateCreator)116 : createUncurried117}) as typeof ZustandExportedTypes.create118119const createStoreUncurried = <T>(120 stateCreator: ZustandExportedTypes.StateCreator<T>,121) => {122 const store = actualCreateStore(stateCreator)123 const initialState = store.getInitialState()124 storeResetFns.add(() => {125 store.setState(initialState, true)126 })127 return store128}129130// when creating a store, we get its initial state, create a reset function and add it in the set131export const createStore = (<T>(132 stateCreator: ZustandExportedTypes.StateCreator<T>,133) => {134 console.log('zustand createStore mock')135136 // to support curried version of createStore137 return typeof stateCreator === 'function'138 ? createStoreUncurried(stateCreator)139 : createStoreUncurried140}) as typeof ZustandExportedTypes.createStore141142// reset all stores after each test run143afterEach(() => {144 act(() => {145 storeResetFns.forEach((resetFn) => {146 resetFn()147 })148 })149})150```151152```ts153// setup-jest.ts154import '@testing-library/jest-dom'155```156157```ts158// jest.config.ts159import type { JestConfigWithTsJest } from 'ts-jest'160161const config: JestConfigWithTsJest = {162 preset: 'ts-jest',163 testEnvironment: 'jsdom',164 setupFilesAfterEnv: ['./setup-jest.ts'],165}166167export default config168```169170> **Note**: to use TypeScript we need to install two packages `ts-jest` and `ts-node`.171172### Vitest173174In the next steps we are going to setup our Vitest environment in order to mock Zustand.175176> **Warning:** In Vitest you can change the [root](https://vitest.dev/config/#root).177> Due to that, you need make sure that you are creating your `__mocks__` directory in the right place.178> Let's say that you change the **root** to `./src`, that means you need to create a `__mocks__`179> directory under `./src`. The end result would be `./src/__mocks__`, rather than `./__mocks__`.180> Creating `__mocks__` directory in the wrong place can lead to issues when using Vitest.181182```ts183// __mocks__/zustand.ts184import { act } from '@testing-library/react'185import type * as ZustandExportedTypes from 'zustand'186export * from 'zustand'187188const { create: actualCreate, createStore: actualCreateStore } =189 await vi.importActual<typeof ZustandExportedTypes>('zustand')190191// a variable to hold reset functions for all stores declared in the app192export const storeResetFns = new Set<() => void>()193194const createUncurried = <T>(195 stateCreator: ZustandExportedTypes.StateCreator<T>,196) => {197 const store = actualCreate(stateCreator)198 const initialState = store.getInitialState()199 storeResetFns.add(() => {200 store.setState(initialState, true)201 })202 return store203}204205// when creating a store, we get its initial state, create a reset function and add it in the set206export const create = (<T>(207 stateCreator: ZustandExportedTypes.StateCreator<T>,208) => {209 console.log('zustand create mock')210211 // to support curried version of create212 return typeof stateCreator === 'function'213 ? createUncurried(stateCreator)214 : createUncurried215}) as typeof ZustandExportedTypes.create216217const createStoreUncurried = <T>(218 stateCreator: ZustandExportedTypes.StateCreator<T>,219) => {220 const store = actualCreateStore(stateCreator)221 const initialState = store.getInitialState()222 storeResetFns.add(() => {223 store.setState(initialState, true)224 })225 return store226}227228// when creating a store, we get its initial state, create a reset function and add it in the set229export const createStore = (<T>(230 stateCreator: ZustandExportedTypes.StateCreator<T>,231) => {232 console.log('zustand createStore mock')233234 // to support curried version of createStore235 return typeof stateCreator === 'function'236 ? createStoreUncurried(stateCreator)237 : createStoreUncurried238}) as typeof ZustandExportedTypes.createStore239240// reset all stores after each test run241afterEach(() => {242 act(() => {243 storeResetFns.forEach((resetFn) => {244 resetFn()245 })246 })247})248```249250> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need251> to add `import { afterEach, vi } from 'vitest'` at the top.252253```ts254// global.d.ts255/// <reference types="vite/client" />256/// <reference types="vitest/globals" />257```258259> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we do260> need to remove `/// <reference types="vitest/globals" />`.261262```ts263// setup-vitest.ts264import '@testing-library/jest-dom/vitest'265266vi.mock('zustand') // to make it work like Jest (auto-mocking)267```268269> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need270> to add `import { vi } from 'vitest'` at the top.271272```ts273// vitest.config.ts274import { defineConfig, mergeConfig } from 'vitest/config'275import viteConfig from './vite.config'276277export default defineConfig((configEnv) =>278 mergeConfig(279 viteConfig(configEnv),280 defineConfig({281 test: {282 globals: true,283 environment: 'jsdom',284 setupFiles: ['./setup-vitest.ts'],285 },286 }),287 ),288)289```290291### Testing Components292293In the next examples we are going to use `useCounterStore`294295> **Note**: all of these examples are written using TypeScript.296297```ts298// shared/counter-store-creator.ts299import { type StateCreator } from 'zustand'300301export type CounterStore = {302 count: number303 inc: () => void304}305306export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({307 count: 1,308 inc: () => set((state) => ({ count: state.count + 1 })),309})310```311312```ts313// stores/use-counter-store.ts314import { create } from 'zustand'315316import {317 type CounterStore,318 counterStoreCreator,319} from '../shared/counter-store-creator'320321export const useCounterStore = create<CounterStore>()(counterStoreCreator)322```323324```tsx325// contexts/use-counter-store-context.tsx326import { type ReactNode, createContext, useContext, useState } from 'react'327import { createStore } from 'zustand'328import { useStoreWithEqualityFn } from 'zustand/traditional'329import { shallow } from 'zustand/shallow'330331import {332 type CounterStore,333 counterStoreCreator,334} from '../shared/counter-store-creator'335336export const createCounterStore = () => {337 return createStore<CounterStore>(counterStoreCreator)338}339340export type CounterStoreApi = ReturnType<typeof createCounterStore>341342export const CounterStoreContext = createContext<CounterStoreApi | undefined>(343 undefined,344)345346export interface CounterStoreProviderProps {347 children: ReactNode348}349350export const CounterStoreProvider = ({351 children,352}: CounterStoreProviderProps) => {353 const [store] = useState(() => createCounterStore())354 return (355 <CounterStoreContext.Provider value={store}>356 {children}357 </CounterStoreContext.Provider>358 )359}360361export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T362363export const useCounterStoreContext = <T,>(364 selector: UseCounterStoreContextSelector<T>,365): T => {366 const counterStoreContext = useContext(CounterStoreContext)367368 if (counterStoreContext === undefined) {369 throw new Error(370 'useCounterStoreContext must be used within CounterStoreProvider',371 )372 }373374 return useStoreWithEqualityFn(counterStoreContext, selector, shallow)375}376```377378```tsx379// components/counter/counter.tsx380import { useCounterStore } from '../../stores/use-counter-store'381382export function Counter() {383 const { count, inc } = useCounterStore()384385 return (386 <div>387 <h2>Counter Store</h2>388 <h4>{count}</h4>389 <button onClick={inc}>One Up</button>390 </div>391 )392}393```394395```ts396// components/counter/index.ts397export * from './counter'398```399400```tsx401// components/counter/counter.test.tsx402import { act, render, screen } from '@testing-library/react'403import userEvent from '@testing-library/user-event'404405import { Counter } from './counter'406407describe('Counter', () => {408 test('should render with initial state of 1', async () => {409 renderCounter()410411 expect(await screen.findByText(/^1$/)).toBeInTheDocument()412 expect(413 await screen.findByRole('button', { name: /one up/i }),414 ).toBeInTheDocument()415 })416417 test('should increase count by clicking a button', async () => {418 const user = userEvent.setup()419420 renderCounter()421422 expect(await screen.findByText(/^1$/)).toBeInTheDocument()423424 await user.click(await screen.findByRole('button', { name: /one up/i }))425426 expect(await screen.findByText(/^2$/)).toBeInTheDocument()427 })428})429430const renderCounter = () => {431 return render(<Counter />)432}433```434435```tsx436// components/counter-with-context/counter-with-context.tsx437import {438 CounterStoreProvider,439 useCounterStoreContext,440} from '../../contexts/use-counter-store-context'441442const Counter = () => {443 const { count, inc } = useCounterStoreContext((state) => state)444445 return (446 <div>447 <h2>Counter Store Context</h2>448 <h4>{count}</h4>449 <button onClick={inc}>One Up</button>450 </div>451 )452}453454export const CounterWithContext = () => {455 return (456 <CounterStoreProvider>457 <Counter />458 </CounterStoreProvider>459 )460}461```462463```tsx464// components/counter-with-context/index.ts465export * from './counter-with-context'466```467468```tsx469// components/counter-with-context/counter-with-context.test.tsx470import { act, render, screen } from '@testing-library/react'471import userEvent from '@testing-library/user-event'472473import { CounterWithContext } from './counter-with-context'474475describe('CounterWithContext', () => {476 test('should render with initial state of 1', async () => {477 renderCounterWithContext()478479 expect(await screen.findByText(/^1$/)).toBeInTheDocument()480 expect(481 await screen.findByRole('button', { name: /one up/i }),482 ).toBeInTheDocument()483 })484485 test('should increase count by clicking a button', async () => {486 const user = userEvent.setup()487488 renderCounterWithContext()489490 expect(await screen.findByText(/^1$/)).toBeInTheDocument()491492 await user.click(await screen.findByRole('button', { name: /one up/i }))493494 expect(await screen.findByText(/^2$/)).toBeInTheDocument()495 })496})497498const renderCounterWithContext = () => {499 return render(<CounterWithContext />)500}501```502503> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need504> to add `import { describe, test, expect } from 'vitest'` at the top of each test file.505506### Testing Stores507508In the next examples we are going to use `useCounterStore`509510> **Note**: all of these examples are written using TypeScript.511512```ts513// shared/counter-store-creator.ts514import { type StateCreator } from 'zustand'515516export type CounterStore = {517 count: number518 inc: () => void519}520521export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({522 count: 1,523 inc: () => set((state) => ({ count: state.count + 1 })),524})525```526527```ts528// stores/use-counter-store.ts529import { create } from 'zustand'530531import {532 type CounterStore,533 counterStoreCreator,534} from '../shared/counter-store-creator'535536export const useCounterStore = create<CounterStore>()(counterStoreCreator)537```538539```tsx540// contexts/use-counter-store-context.tsx541import { type ReactNode, createContext, useContext, useState } from 'react'542import { createStore } from 'zustand'543import { useStoreWithEqualityFn } from 'zustand/traditional'544import { shallow } from 'zustand/shallow'545546import {547 type CounterStore,548 counterStoreCreator,549} from '../shared/counter-store-creator'550551export const createCounterStore = () => {552 return createStore<CounterStore>(counterStoreCreator)553}554555export type CounterStoreApi = ReturnType<typeof createCounterStore>556557export const CounterStoreContext = createContext<CounterStoreApi | undefined>(558 undefined,559)560561export interface CounterStoreProviderProps {562 children: ReactNode563}564565export const CounterStoreProvider = ({566 children,567}: CounterStoreProviderProps) => {568 const [store] = useState(() => createCounterStore())569 return (570 <CounterStoreContext.Provider value={store}>571 {children}572 </CounterStoreContext.Provider>573 )574}575576export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T577578export const useCounterStoreContext = <T,>(579 selector: UseCounterStoreContextSelector<T>,580): T => {581 const counterStoreContext = useContext(CounterStoreContext)582583 if (counterStoreContext === undefined) {584 throw new Error(585 'useCounterStoreContext must be used within CounterStoreProvider',586 )587 }588589 return useStoreWithEqualityFn(counterStoreContext, selector, shallow)590}591```592593```tsx594// components/counter/counter.tsx595import { useCounterStore } from '../../stores/use-counter-store'596597export function Counter() {598 const { count, inc } = useCounterStore()599600 return (601 <div>602 <h2>Counter Store</h2>603 <h4>{count}</h4>604 <button onClick={inc}>One Up</button>605 </div>606 )607}608```609610```ts611// components/counter/index.ts612export * from './counter'613```614615```tsx616// components/counter/counter.test.tsx617import { act, render, screen } from '@testing-library/react'618import userEvent from '@testing-library/user-event'619620import { Counter, useCounterStore } from '../../../stores/use-counter-store.ts'621622describe('Counter', () => {623 test('should render with initial state of 1', async () => {624 renderCounter()625626 expect(useCounterStore.getState().count).toBe(1)627 })628629 test('should increase count by clicking a button', async () => {630 const user = userEvent.setup()631632 renderCounter()633634 expect(useCounterStore.getState().count).toBe(1)635636 await user.click(await screen.findByRole('button', { name: /one up/i }))637638 expect(useCounterStore.getState().count).toBe(2)639 })640})641642const renderCounter = () => {643 return render(<Counter />)644}645```646647```tsx648// components/counter-with-context/counter-with-context.tsx649import {650 CounterStoreProvider,651 useCounterStoreContext,652} from '../../contexts/use-counter-store-context'653654const Counter = () => {655 const { count, inc } = useCounterStoreContext((state) => state)656657 return (658 <div>659 <h2>Counter Store Context</h2>660 <h4>{count}</h4>661 <button onClick={inc}>One Up</button>662 </div>663 )664}665666export const CounterWithContext = () => {667 return (668 <CounterStoreProvider>669 <Counter />670 </CounterStoreProvider>671 )672}673```674675```tsx676// components/counter-with-context/index.ts677export * from './counter-with-context'678```679680```tsx681// components/counter-with-context/counter-with-context.test.tsx682import { act, render, screen } from '@testing-library/react'683import userEvent from '@testing-library/user-event'684685import { CounterStoreContext } from '../../../contexts/use-counter-store-context'686import { counterStoreCreator } from '../../../shared/counter-store-creator'687688describe('CounterWithContext', () => {689 test('should render with initial state of 1', async () => {690 const counterStore = counterStoreCreator()691692 renderCounterWithContext(counterStore)693694 expect(counterStore.getState().count).toBe(1)695 expect(696 await screen.findByRole('button', { name: /one up/i }),697 ).toBeInTheDocument()698 })699700 test('should increase count by clicking a button', async () => {701 const user = userEvent.setup()702 const counterStore = counterStoreCreator()703704 renderCounterWithContext(counterStore)705706 expect(counterStore.getState().count).toBe(1)707708 await user.click(await screen.findByRole('button', { name: /one up/i }))709710 expect(counterStore.getState().count).toBe(2)711 })712})713714const renderCounterWithContext = (store) => {715 return render(<CounterWithContext />, {716 wrapper: ({ children }) => (717 <CounterStoreContext.Provider value={store}>718 {children}719 </CounterStoreContext.Provider>720 ),721 })722}723```724725## References726727- **React Testing Library**: [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)728 is a very lightweight solution for testing React components. It provides utility functions on top729 of `react-dom` and `react-dom/test-utils`, in a way that encourages better testing practices. Its730 primary guiding principle is: "The more your tests resemble the way your software is used, the731 more confidence they can give you."732- **Native Testing Library**: [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)733 is a very lightweight solution for testing React Native components, similarly to RTL, but its734 functions are built on top of `react-test-renderer`.735- **Testing Implementation Details**: Blog post by Kent C. Dodds on why he recommends to avoid736 [testing implementation details](https://kentcdodds.com/blog/testing-implementation-details).737738## Demos739740- Jest: https://stackblitz.com/edit/jest-zustand741- Vitest: https://stackblitz.com/edit/vitest-zustand
added:docs/learn/guides/tutorial-tic-tac-toe.md+1429 added
1---2title: 'Tutorial: Tic-Tac-Toe'3description: Building a game4nav: 35---67# Tutorial: Tic-Tac-Toe89## Building a game1011You will build a small tic-tac-toe game during this tutorial. This tutorial does assume existing12React knowledge. The techniques you'll learn in the tutorial are fundamental to building any React13app, and fully understanding it will give you a deep understanding of React and Zustand.1415> [!NOTE]16> This tutorial is crafted for those who learn best through hands-on experience and want to swiftly17> create something tangible. It draws inspiration from React's tic-tac-toe tutorial.1819The tutorial is divided into several sections:2021- Setup for the tutorial will give you a starting point to follow the tutorial.22- Overview will teach you the fundamentals of React: components, props, and state.23- Completing the game will teach you the most common techniques in React development.24- Adding time travel will give you a deeper insight into the unique strengths of React.2526### What are you building?2728In this tutorial, you'll build an interactive tic-tac-toe game with React and Zustand.2930You can see what it will look like when you're finished here:3132```jsx33import { create } from 'zustand'34import { combine } from 'zustand/middleware'3536const useGameStore = create(37 combine(38 {39 history: [Array(9).fill(null)],40 currentMove: 0,41 },42 (set, get) => {43 return {44 setHistory: (nextHistory) => {45 set((state) => ({46 history:47 typeof nextHistory === 'function'48 ? nextHistory(state.history)49 : nextHistory,50 }))51 },52 setCurrentMove: (nextCurrentMove) => {53 set((state) => ({54 currentMove:55 typeof nextCurrentMove === 'function'56 ? nextCurrentMove(state.currentMove)57 : nextCurrentMove,58 }))59 },60 }61 },62 ),63)6465function Square({ value, onSquareClick }) {66 return (67 <button68 style={{69 display: 'inline-flex',70 alignItems: 'center',71 justifyContent: 'center',72 padding: 0,73 backgroundColor: '#fff',74 border: '1px solid #999',75 outline: 0,76 borderRadius: 0,77 fontSize: '1rem',78 fontWeight: 'bold',79 }}80 onClick={onSquareClick}81 >82 {value}83 </button>84 )85}8687function Board({ xIsNext, squares, onPlay }) {88 const winner = calculateWinner(squares)89 const turns = calculateTurns(squares)90 const player = xIsNext ? 'X' : 'O'91 const status = calculateStatus(winner, turns, player)9293 function handleClick(i) {94 if (squares[i] || winner) return95 const nextSquares = squares.slice()96 nextSquares[i] = player97 onPlay(nextSquares)98 }99100 return (101 <>102 <div style={{ marginBottom: '0.5rem' }}>{status}</div>103 <div104 style={{105 display: 'grid',106 gridTemplateColumns: 'repeat(3, 1fr)',107 gridTemplateRows: 'repeat(3, 1fr)',108 width: 'calc(3 * 2.5rem)',109 height: 'calc(3 * 2.5rem)',110 border: '1px solid #999',111 }}112 >113 {squares.map((_, i) => (114 <Square115 key={`square-${i}`}116 value={squares[i]}117 onSquareClick={() => handleClick(i)}118 />119 ))}120 </div>121 </>122 )123}124125export default function Game() {126 const history = useGameStore((state) => state.history)127 const setHistory = useGameStore((state) => state.setHistory)128 const currentMove = useGameStore((state) => state.currentMove)129 const setCurrentMove = useGameStore((state) => state.setCurrentMove)130 const xIsNext = currentMove % 2 === 0131 const currentSquares = history[currentMove]132133 function handlePlay(nextSquares) {134 const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]135 setHistory(nextHistory)136 setCurrentMove(nextHistory.length - 1)137 }138139 function jumpTo(nextMove) {140 setCurrentMove(nextMove)141 }142143 return (144 <div145 style={{146 display: 'flex',147 flexDirection: 'row',148 fontFamily: 'monospace',149 }}150 >151 <div>152 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />153 </div>154 <div style={{ marginLeft: '1rem' }}>155 <ol>156 {history.map((_, historyIndex) => {157 const description =158 historyIndex > 0159 ? `Go to move #${historyIndex}`160 : 'Go to game start'161162 return (163 <li key={historyIndex}>164 <button onClick={() => jumpTo(historyIndex)}>165 {description}166 </button>167 </li>168 )169 })}170 </ol>171 </div>172 </div>173 )174}175176function calculateWinner(squares) {177 const lines = [178 [0, 1, 2],179 [3, 4, 5],180 [6, 7, 8],181 [0, 3, 6],182 [1, 4, 7],183 [2, 5, 8],184 [0, 4, 8],185 [2, 4, 6],186 ]187188 for (let i = 0; i < lines.length; i++) {189 const [a, b, c] = lines[i]190 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {191 return squares[a]192 }193 }194195 return null196}197198function calculateTurns(squares) {199 return squares.filter((square) => !square).length200}201202function calculateStatus(winner, turns, player) {203 if (!winner && !turns) return 'Draw'204 if (winner) return `Winner ${winner}`205 return `Next player: ${player}`206}207```208209### Building the board210211Let's start by creating the `Square` component, which will be a building block for our `Board`212component. This component will represent each square in our game.213214The `Square` component should take `value` and `onSquareClick` as props. It should return a215`<button>` element, styled to look like a square. The button displays the value prop, which can be216`'X'`, `'O'`, or `null`, depending on the game's state. When the button is clicked, it triggers the217`onSquareClick` function passed in as a prop, allowing the game to respond to user input.218219Here's the code for the `Square` component:220221```jsx222function Square({ value, onSquareClick }) {223 return (224 <button225 style={{226 display: 'inline-flex',227 alignItems: 'center',228 justifyContent: 'center',229 padding: 0,230 backgroundColor: '#fff',231 border: '1px solid #999',232 outline: 0,233 borderRadius: 0,234 fontSize: '1rem',235 fontWeight: 'bold',236 }}237 onClick={onSquareClick}238 >239 {value}240 </button>241 )242}243```244245Let's move on to creating the Board component, which will consist of 9 squares arranged in a grid.246This component will serve as the main playing area for our game.247248The `Board` component should return a `<div>` element styled as a grid. The grid layout is achieved249using CSS Grid, with three columns and three rows, each taking up an equal fraction of the available250space. The overall size of the grid is determined by the width and height properties, ensuring that251it is square-shaped and appropriately sized.252253Inside the grid, we place nine Square components, each with a value prop representing its position.254These Square components will eventually hold the game symbols (`'X'` or `'O'`) and handle user255interactions.256257Here's the code for the `Board` component:258259```jsx260export default function Board() {261 return (262 <div263 style={{264 display: 'grid',265 gridTemplateColumns: 'repeat(3, 1fr)',266 gridTemplateRows: 'repeat(3, 1fr)',267 width: 'calc(3 * 2.5rem)',268 height: 'calc(3 * 2.5rem)',269 border: '1px solid #999',270 }}271 >272 <Square value="1" />273 <Square value="2" />274 <Square value="3" />275 <Square value="4" />276 <Square value="5" />277 <Square value="6" />278 <Square value="7" />279 <Square value="8" />280 <Square value="9" />281 </div>282 )283}284```285286This Board component sets up the basic structure for our game board by arranging nine squares in a2873x3 grid. It positions the squares neatly, providing a foundation for adding more features and288handling player interactions in the future.289290### Lifting state up291292Each `Square` component could maintain a part of the game's state. To check for a winner in a293tic-tac-toe game, the `Board` component would need to somehow know the state of each of the 9294`Square` components.295296How would you approach that? At first, you might guess that the `Board` component needs to ask each297`Square` component for that `Square`'s component state. Although this approach is technically298possible in React, we discourage it because the code becomes difficult to understand, susceptible299to bugs, and hard to refactor. Instead, the best approach is to store the game's state in the300parent `Board` component instead of in each `Square` component. The `Board` component can tell each301`Square` component what to display by passing a prop, like you did when you passed a number to each302`Square` component.303304> [!IMPORTANT]305> To collect data from multiple children, or to have two or more child components306> communicate with each other, declare the shared state in their parent component instead. The307> parent component can pass that state back down to the children via props. This keeps the child308> components in sync with each other and with their parent.309310Let's take this opportunity to try it out. Edit the `Board` component so that it declares a state311variable named squares that defaults to an array of 9 nulls corresponding to the 9 squares:312313```jsx314import { create } from 'zustand'315import { combine } from 'zustand/middleware'316317const useGameStore = create(318 combine({ squares: Array(9).fill(null) }, (set) => {319 return {320 setSquares: (nextSquares) => {321 set((state) => ({322 squares:323 typeof nextSquares === 'function'324 ? nextSquares(state.squares)325 : nextSquares,326 }))327 },328 }329 }),330)331332export default function Board() {333 const squares = useGameStore((state) => state.squares)334 const setSquares = useGameStore((state) => state.setSquares)335336 return (337 <div338 style={{339 display: 'grid',340 gridTemplateColumns: 'repeat(3, 1fr)',341 gridTemplateRows: 'repeat(3, 1fr)',342 width: 'calc(3 * 2.5rem)',343 height: 'calc(3 * 2.5rem)',344 border: '1px solid #999',345 }}346 >347 {squares.map((square, squareIndex) => (348 <Square key={squareIndex} value={square} />349 ))}350 </div>351 )352}353```354355`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The356`useGameStore` declares a `squares` state that's initially set to that array. Each entry in the357array corresponds to the value of a square. When you fill the board in later, the squares array358will look like this:359360```js361const squares = ['O', null, 'X', 'X', 'X', 'O', 'O', null, null]362```363364Each Square will now receive a `value` prop that will either be `'X'`, `'O'`, or `null` for empty365squares.366367Next, you need to change what happens when a `Square` component is clicked. The `Board` component368now maintains which squares are filled. You'll need to create a way for the `Square` component to369update the `Board`'s component state. Since state is private to a component that defines it, you370cannot update the `Board`'s component state directly from `Square` component.371372Instead, you'll pass down a function from the Board component to the `Square` component, and you'll373have `Square` component call that function when a square is clicked. You'll start with the function374that the `Square` component will call when it is clicked. You'll call that function `onSquareClick`:375376Now you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name377`handleClick`. To connect `onSquareClick` to `handleClick` you'll pass an inline function to the378`onSquareClick` prop of the first Square component:379380```jsx381<Square key={squareIndex} value={square} onSquareClick={() => handleClick(i)} />382```383384Lastly, you will define the `handleClick` function inside the `Board` component to update the385squares array holding your board's state.386387The `handleClick` function should take the index of the square to update and create a copy of the388`squares` array (`nextSquares`). Then, `handleClick` updates the `nextSquares` array by adding `X`389to the square at the specified index (`i`) if is not already filled.390391```jsx {5-10,27}392export default function Board() {393 const squares = useGameStore((state) => state.squares)394 const setSquares = useGameStore((state) => state.setSquares)395396 function handleClick(i) {397 if (squares[i]) return398 const nextSquares = squares.slice()399 nextSquares[i] = 'X'400 setSquares(nextSquares)401 }402403 return (404 <div405 style={{406 display: 'grid',407 gridTemplateColumns: 'repeat(3, 1fr)',408 gridTemplateRows: 'repeat(3, 1fr)',409 width: 'calc(3 * 2.5rem)',410 height: 'calc(3 * 2.5rem)',411 border: '1px solid #999',412 }}413 >414 {squares.map((square, squareIndex) => (415 <Square416 key={squareIndex}417 value={square}418 onSquareClick={() => handleClick(squareIndex)}419 />420 ))}421 </div>422 )423}424```425426> [!IMPORTANT]427> Note how in `handleClick` function, you call `.slice()` to create a copy of the squares array428> instead of modifying the existing array.429430### Taking turns431432It's now time to fix a major defect in this tic-tac-toe game: the `'O'`s cannot be used on the433board.434435You'll set the first move to be `'X'` by default. Let's keep track of this by adding another piece436of state to the `useGameStore` hook:437438```jsx {2,12-18}439const useGameStore = create(440 combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {441 return {442 setSquares: (nextSquares) => {443 set((state) => ({444 squares:445 typeof nextSquares === 'function'446 ? nextSquares(state.squares)447 : nextSquares,448 }))449 },450 setXIsNext: (nextXIsNext) => {451 set((state) => ({452 xIsNext:453 typeof nextXIsNext === 'function'454 ? nextXIsNext(state.xIsNext)455 : nextXIsNext,456 }))457 },458 }459 }),460)461```462463Each time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next464and the game's state will be saved. You'll update the Board's `handleClick` function to flip the465value of `xIsNext`:466467```jsx {2-3,6,11}468export default function Board() {469 const xIsNext = useGameStore((state) => state.xIsNext)470 const setXIsNext = useGameStore((state) => state.setXIsNext)471 const squares = useGameStore((state) => state.squares)472 const setSquares = useGameStore((state) => state.setSquares)473 const player = xIsNext ? 'X' : 'O'474475 function handleClick(i) {476 if (squares[i]) return477 const nextSquares = squares.slice()478 nextSquares[i] = player479 setSquares(nextSquares)480 setXIsNext(!xIsNext)481 }482483 return (484 <div485 style={{486 display: 'grid',487 gridTemplateColumns: 'repeat(3, 1fr)',488 gridTemplateRows: 'repeat(3, 1fr)',489 width: 'calc(3 * 2.5rem)',490 height: 'calc(3 * 2.5rem)',491 border: '1px solid #999',492 }}493 >494 {squares.map((square, squareIndex) => (495 <Square496 key={squareIndex}497 value={square}498 onSquareClick={() => handleClick(squareIndex)}499 />500 ))}501 </div>502 )503}504```505506### Declaring a winner or draw507508Now that the players can take turns, you'll want to show when the game is won or drawn and there509are no more turns to make. To do this you'll add three helper functions. The first helper function510called `calculateWinner` that takes an array of 9 squares, checks for a winner and returns `'X'`,511`'O'`, or `null` as appropriate. The second helper function called `calculateTurns` that takes the512same array, checks for remaining turns by filtering out only `null` items, and returns the count of513them. The last helper called `calculateStatus` that takes the remaining turns, the winner, and the514current player (`'X' or 'O'`):515516```js517function calculateWinner(squares) {518 const lines = [519 [0, 1, 2],520 [3, 4, 5],521 [6, 7, 8],522 [0, 3, 6],523 [1, 4, 7],524 [2, 5, 8],525 [0, 4, 8],526 [2, 4, 6],527 ]528529 for (let i = 0; i < lines.length; i++) {530 const [a, b, c] = lines[i]531 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {532 return squares[a]533 }534 }535536 return null537}538539function calculateTurns(squares) {540 return squares.filter((square) => !square).length541}542543function calculateStatus(winner, turns, player) {544 if (!winner && !turns) return 'Draw'545 if (winner) return `Winner ${winner}`546 return `Next player: ${player}`547}548```549550You will use the result of `calculateWinner(squares)` in the Board component's `handleClick`551function to check if a player has won. You can perform this check at the same time you check if a552user has clicked a square that already has a `'X'` or and `'O'`. We'd like to return early in553both cases:554555```js {2}556function handleClick(i) {557 if (squares[i] || winner) return558 const nextSquares = squares.slice()559 nextSquares[i] = player560 setSquares(nextSquares)561 setXIsNext(!xIsNext)562}563```564565To let the players know when the game is over, you can display text such as `'Winner: X'` or566`'Winner: O'`. To do that you'll add a `status` section to the `Board` component. The status will567display the winner or draw if the game is over and if the game is ongoing you'll display which568player's turn is next:569570```jsx {6-7,9,21}571export default function Board() {572 const xIsNext = useGameStore((state) => state.xIsNext)573 const setXIsNext = useGameStore((state) => state.setXIsNext)574 const squares = useGameStore((state) => state.squares)575 const setSquares = useGameStore((state) => state.setSquares)576 const winner = calculateWinner(squares)577 const turns = calculateTurns(squares)578 const player = xIsNext ? 'X' : 'O'579 const status = calculateStatus(winner, turns, player)580581 function handleClick(i) {582 if (squares[i] || winner) return583 const nextSquares = squares.slice()584 nextSquares[i] = player585 setSquares(nextSquares)586 setXIsNext(!xIsNext)587 }588589 return (590 <>591 <div style={{ marginBottom: '0.5rem' }}>{status}</div>592 <div593 style={{594 display: 'grid',595 gridTemplateColumns: 'repeat(3, 1fr)',596 gridTemplateRows: 'repeat(3, 1fr)',597 width: 'calc(3 * 2.5rem)',598 height: 'calc(3 * 2.5rem)',599 border: '1px solid #999',600 }}601 >602 {squares.map((square, squareIndex) => (603 <Square604 key={squareIndex}605 value={square}606 onSquareClick={() => handleClick(squareIndex)}607 />608 ))}609 </div>610 </>611 )612}613```614615Congratulations! You now have a working tic-tac-toe game. And you've just learned the basics of616React and Zustand too. So you are the real winner here. Here is what the code should look like:617618```jsx619import { create } from 'zustand'620import { combine } from 'zustand/middleware'621622const useGameStore = create(623 combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {624 return {625 setSquares: (nextSquares) => {626 set((state) => ({627 squares:628 typeof nextSquares === 'function'629 ? nextSquares(state.squares)630 : nextSquares,631 }))632 },633 setXIsNext: (nextXIsNext) => {634 set((state) => ({635 xIsNext:636 typeof nextXIsNext === 'function'637 ? nextXIsNext(state.xIsNext)638 : nextXIsNext,639 }))640 },641 }642 }),643)644645function Square({ value, onSquareClick }) {646 return (647 <button648 style={{649 display: 'inline-flex',650 alignItems: 'center',651 justifyContent: 'center',652 padding: 0,653 backgroundColor: '#fff',654 border: '1px solid #999',655 outline: 0,656 borderRadius: 0,657 fontSize: '1rem',658 fontWeight: 'bold',659 }}660 onClick={onSquareClick}661 >662 {value}663 </button>664 )665}666667export default function Board() {668 const xIsNext = useGameStore((state) => state.xIsNext)669 const setXIsNext = useGameStore((state) => state.setXIsNext)670 const squares = useGameStore((state) => state.squares)671 const setSquares = useGameStore((state) => state.setSquares)672 const winner = calculateWinner(squares)673 const turns = calculateTurns(squares)674 const player = xIsNext ? 'X' : 'O'675 const status = calculateStatus(winner, turns, player)676677 function handleClick(i) {678 if (squares[i] || winner) return679 const nextSquares = squares.slice()680 nextSquares[i] = player681 setSquares(nextSquares)682 setXIsNext(!xIsNext)683 }684685 return (686 <>687 <div style={{ marginBottom: '0.5rem' }}>{status}</div>688 <div689 style={{690 display: 'grid',691 gridTemplateColumns: 'repeat(3, 1fr)',692 gridTemplateRows: 'repeat(3, 1fr)',693 width: 'calc(3 * 2.5rem)',694 height: 'calc(3 * 2.5rem)',695 border: '1px solid #999',696 }}697 >698 {squares.map((square, squareIndex) => (699 <Square700 key={squareIndex}701 value={square}702 onSquareClick={() => handleClick(squareIndex)}703 />704 ))}705 </div>706 </>707 )708}709710function calculateWinner(squares) {711 const lines = [712 [0, 1, 2],713 [3, 4, 5],714 [6, 7, 8],715 [0, 3, 6],716 [1, 4, 7],717 [2, 5, 8],718 [0, 4, 8],719 [2, 4, 6],720 ]721722 for (let i = 0; i < lines.length; i++) {723 const [a, b, c] = lines[i]724 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {725 return squares[a]726 }727 }728729 return null730}731732function calculateTurns(squares) {733 return squares.filter((square) => !square).length734}735736function calculateStatus(winner, turns, player) {737 if (!winner && !turns) return 'Draw'738 if (winner) return `Winner ${winner}`739 return `Next player: ${player}`740}741```742743### Adding time travel744745As a final exercise, let's make it possible to “go back in time” and revisit previous moves in the746game.747748If you had directly modified the squares array, implementing this time-travel feature would be very749difficult. However, since you used `slice()` to create a new copy of the squares array after every750move, treating it as immutable, you can store every past version of the squares array and navigate751between them.752753You'll keep track of these past squares arrays in a new state variable called `history`. This754`history` array will store all board states, from the first move to the latest one, and will look755something like this:756757```js758const history = [759 // First move760 [null, null, null, null, null, null, null, null, null],761 // Second move762 ['X', null, null, null, null, null, null, null, null],763 // Third move764 ['X', 'O', null, null, null, null, null, null, null],765 // and so on...766]767```768769This approach allows you to easily navigate between different game states and implement the770time-travel feature.771772### Lifting state up, again773774Next, you will create a new top-level component called `Game` to display a list of past moves. This775is where you will store the `history` state that contains the entire game history.776777By placing the `history` state in the `Game` component, you can remove the `squares` state from the778`Board` component. You will now lift the state up from the `Board` component to the top-level `Game`779component. This change allows the `Game` component to have full control over the `Board`'s780component data and instruct the `Board` component to render previous turns from the `history`.781782First, add a `Game` component with `export default` and remove it from `Board` component. Here is783what the code should look like:784785```jsx {1,44-61}786function Board() {787 const xIsNext = useGameStore((state) => state.xIsNext)788 const setXIsNext = useGameStore((state) => state.setXIsNext)789 const squares = useGameStore((state) => state.squares)790 const setSquares = useGameStore((state) => state.setSquares)791 const winner = calculateWinner(squares)792 const turns = calculateTurns(squares)793 const player = xIsNext ? 'X' : 'O'794 const status = calculateStatus(winner, turns, player)795796 function handleClick(i) {797 if (squares[i] || winner) return798 const nextSquares = squares.slice()799 nextSquares[i] = player800 setSquares(nextSquares)801 setXIsNext(!xIsNext)802 }803804 return (805 <>806 <div style={{ marginBottom: '0.5rem' }}>{status}</div>807 <div808 style={{809 display: 'grid',810 gridTemplateColumns: 'repeat(3, 1fr)',811 gridTemplateRows: 'repeat(3, 1fr)',812 width: 'calc(3 * 2.5rem)',813 height: 'calc(3 * 2.5rem)',814 border: '1px solid #999',815 }}816 >817 {squares.map((square, squareIndex) => (818 <Square819 key={squareIndex}820 value={square}821 onSquareClick={() => handleClick(squareIndex)}822 />823 ))}824 </div>825 </>826 )827}828829export default function Game() {830 return (831 <div832 style={{833 display: 'flex',834 flexDirection: 'row',835 fontFamily: 'monospace',836 }}837 >838 <div>839 <Board />840 </div>841 <div style={{ marginLeft: '1rem' }}>842 <ol>{/* TODO */}</ol>843 </div>844 </div>845 )846}847```848849Add some state to the `useGameStore` hook to track the history of moves:850851```js {2,4-11}852const useGameStore = create(853 combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {854 return {855 setHistory: (nextHistory) => {856 set((state) => ({857 history:858 typeof nextHistory === 'function'859 ? nextHistory(state.history)860 : nextHistory,861 }))862 },863 setXIsNext: (nextXIsNext) => {864 set((state) => ({865 xIsNext:866 typeof nextXIsNext === 'function'867 ? nextXIsNext(state.xIsNext)868 : nextXIsNext,869 }))870 },871 }872 }),873)874```875876Notice how `[Array(9).fill(null)]` creates an array with a single item, which is itself an array of8779 null values.878879To render the squares for the current move, you'll need to read the most recent squares array from880the `history` state. You don't need an extra state for this because you already have enough881information to calculate it during rendering:882883```jsx {2-6}884export default function Game() {885 const history = useGameStore((state) => state.history)886 const setHistory = useGameStore((state) => state.setHistory)887 const xIsNext = useGameStore((state) => state.xIsNext)888 const setXIsNext = useGameStore((state) => state.setXIsNext)889 const currentSquares = history[history.length - 1]890891 return (892 <div893 style={{894 display: 'flex',895 flexDirection: 'row',896 fontFamily: 'monospace',897 }}898 >899 <div>900 <Board />901 </div>902 <div style={{ marginLeft: '1rem' }}>903 <ol>{/*TODO*/}</ol>904 </div>905 </div>906 )907}908```909910Next, create a `handlePlay` function inside the `Game` component that will be called by the `Board`911component to update the game. Pass `xIsNext`, `currentSquares` and `handlePlay` as props to the912`Board` component:913914```jsx {8-10,21}915export default function Game() {916 const history = useGameStore((state) => state.history)917 const setHistory = useGameStore((state) => state.setHistory)918 const xIsNext = useGameStore((state) => state.xIsNext)919 const setXIsNext = useGameStore((state) => state.setXIsNext)920 const currentSquares = history[history.length - 1]921922 function handlePlay(nextSquares) {923 // TODO924 }925926 return (927 <div928 style={{929 display: 'flex',930 flexDirection: 'row',931 fontFamily: 'monospace',932 }}933 >934 <div>935 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />936 </div>937 <div style={{ marginLeft: '1rem' }}>938 <ol>{/*TODO*/}</ol>939 </div>940 </div>941 )942}943```944945Let's make the `Board` component fully controlled by the props it receives. To do this, we'll modify946the `Board` component to accept three props: `xIsNext`, `squares`, and a new `onPlay` function that947the `Board` component can call with the updated squares array when a player makes a move.948949```jsx {1}950function Board({ xIsNext, squares, onPlay }) {951 const winner = calculateWinner(squares)952 const turns = calculateTurns(squares)953 const player = xIsNext ? 'X' : 'O'954 const status = calculateStatus(winner, turns, player)955956 function handleClick(i) {957 if (squares[i] || winner) return958 const nextSquares = squares.slice()959 nextSquares[i] = player960 onPlay(nextSquares)961 }962963 return (964 <>965 <div style={{ marginBottom: '0.5rem' }}>{status}</div>966 <div967 style={{968 display: 'grid',969 gridTemplateColumns: 'repeat(3, 1fr)',970 gridTemplateRows: 'repeat(3, 1fr)',971 width: 'calc(3 * 2.5rem)',972 height: 'calc(3 * 2.5rem)',973 border: '1px solid #999',974 }}975 >976 {squares.map((square, squareIndex) => (977 <Square978 key={squareIndex}979 value={square}980 onSquareClick={() => handleClick(squareIndex)}981 />982 ))}983 </div>984 </>985 )986}987```988989The `Board` component is now fully controlled by the props passed to it by the `Game` component. To990get the game working again, you need to implement the `handlePlay` function in the `Game`991component.992993What should `handlePlay` do when called? Previously, the `Board` component called `setSquares` with994an updated array; now it passes the updated squares array to `onPlay`.995996The `handlePlay` function needs to update the `Game` component's state to trigger a re-render.997Instead of using `setSquares`, you'll update the `history` state variable by appending the updated998squares array as a new `history` entry. You also need to toggle `xIsNext`, just as the `Board`999component used1000to do.10011002```js {2-3}1003function handlePlay(nextSquares) {1004 setHistory(history.concat([nextSquares]))1005 setXIsNext(!xIsNext)1006}1007```10081009At this point, you've moved the state to live in the `Game` component, and the UI should be fully1010working, just as it was before the refactor. Here is what the code should look like at this point:10111012```jsx1013import { create } from 'zustand'1014import { combine } from 'zustand/middleware'10151016const useGameStore = create(1017 combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {1018 return {1019 setHistory: (nextHistory) => {1020 set((state) => ({1021 history:1022 typeof nextHistory === 'function'1023 ? nextHistory(state.history)1024 : nextHistory,1025 }))1026 },1027 setXIsNext: (nextXIsNext) => {1028 set((state) => ({1029 xIsNext:1030 typeof nextXIsNext === 'function'1031 ? nextXIsNext(state.xIsNext)1032 : nextXIsNext,1033 }))1034 },1035 }1036 }),1037)10381039function Square({ value, onSquareClick }) {1040 return (1041 <button1042 style={{1043 display: 'inline-flex',1044 alignItems: 'center',1045 justifyContent: 'center',1046 padding: 0,1047 backgroundColor: '#fff',1048 border: '1px solid #999',1049 outline: 0,1050 borderRadius: 0,1051 fontSize: '1rem',1052 fontWeight: 'bold',1053 }}1054 onClick={onSquareClick}1055 >1056 {value}1057 </button>1058 )1059}10601061function Board({ xIsNext, squares, onPlay }) {1062 const winner = calculateWinner(squares)1063 const turns = calculateTurns(squares)1064 const player = xIsNext ? 'X' : 'O'1065 const status = calculateStatus(winner, turns, player)10661067 function handleClick(i) {1068 if (squares[i] || winner) return1069 const nextSquares = squares.slice()1070 nextSquares[i] = player1071 onPlay(nextSquares)1072 }10731074 return (1075 <>1076 <div style={{ marginBottom: '0.5rem' }}>{status}</div>1077 <div1078 style={{1079 display: 'grid',1080 gridTemplateColumns: 'repeat(3, 1fr)',1081 gridTemplateRows: 'repeat(3, 1fr)',1082 width: 'calc(3 * 2.5rem)',1083 height: 'calc(3 * 2.5rem)',1084 border: '1px solid #999',1085 }}1086 >1087 {squares.map((square, squareIndex) => (1088 <Square1089 key={squareIndex}1090 value={square}1091 onSquareClick={() => handleClick(squareIndex)}1092 />1093 ))}1094 </div>1095 </>1096 )1097}10981099export default function Game() {1100 const history = useGameStore((state) => state.history)1101 const setHistory = useGameStore((state) => state.setHistory)1102 const xIsNext = useGameStore((state) => state.xIsNext)1103 const setXIsNext = useGameStore((state) => state.setXIsNext)1104 const currentSquares = history[history.length - 1]11051106 function handlePlay(nextSquares) {1107 setHistory(history.concat([nextSquares]))1108 setXIsNext(!xIsNext)1109 }11101111 return (1112 <div1113 style={{1114 display: 'flex',1115 flexDirection: 'row',1116 fontFamily: 'monospace',1117 }}1118 >1119 <div>1120 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1121 </div>1122 <div style={{ marginLeft: '1rem' }}>1123 <ol>{/*TODO*/}</ol>1124 </div>1125 </div>1126 )1127}11281129function calculateWinner(squares) {1130 const lines = [1131 [0, 1, 2],1132 [3, 4, 5],1133 [6, 7, 8],1134 [0, 3, 6],1135 [1, 4, 7],1136 [2, 5, 8],1137 [0, 4, 8],1138 [2, 4, 6],1139 ]11401141 for (let i = 0; i < lines.length; i++) {1142 const [a, b, c] = lines[i]1143 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {1144 return squares[a]1145 }1146 }11471148 return null1149}11501151function calculateTurns(squares) {1152 return squares.filter((square) => !square).length1153}11541155function calculateStatus(winner, turns, player) {1156 if (!winner && !turns) return 'Draw'1157 if (winner) return `Winner ${winner}`1158 return `Next player: ${player}`1159}1160```11611162### Showing the past moves11631164Since you are recording the tic-tac-toe game's history, you can now display a list of past moves to1165the player.11661167You already have an array of `history` moves in store, so now you need to transform it to an array1168of React elements. In JavaScript, to transform one array into another, you can use the Array1169`.map()` method:11701171You'll use `map` to transform your `history` of moves into React elements representing buttons on the1172screen, and display a list of buttons to **jump** to past moves. Let's `map` over the `history` in1173the `Game` component:11741175```jsx {29-44}1176export default function Game() {1177 const history = useGameStore((state) => state.history)1178 const setHistory = useGameStore((state) => state.setHistory)1179 const xIsNext = useGameStore((state) => state.xIsNext)1180 const setXIsNext = useGameStore((state) => state.setXIsNext)1181 const currentSquares = history[history.length - 1]11821183 function handlePlay(nextSquares) {1184 setHistory(history.concat([nextSquares]))1185 setXIsNext(!xIsNext)1186 }11871188 function jumpTo(nextMove) {1189 // TODO1190 }11911192 return (1193 <div1194 style={{1195 display: 'flex',1196 flexDirection: 'row',1197 fontFamily: 'monospace',1198 }}1199 >1200 <div>1201 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1202 </div>1203 <div style={{ marginLeft: '1rem' }}>1204 <ol>1205 {history.map((_, historyIndex) => {1206 const description =1207 historyIndex > 01208 ? `Go to move #${historyIndex}`1209 : 'Go to game start'12101211 return (1212 <li key={historyIndex}>1213 <button onClick={() => jumpTo(historyIndex)}>1214 {description}1215 </button>1216 </li>1217 )1218 })}1219 </ol>1220 </div>1221 </div>1222 )1223}1224```12251226Before you can implement the `jumpTo` function, you need the `Game` component to keep track of which1227step the user is currently viewing. To do this, define a new state variable called `currentMove`,1228which will start at `0`:12291230```js {3,14-21}1231const useGameStore = create(1232 combine(1233 { history: [Array(9).fill(null)], currentMove: 0, xIsNext: true },1234 (set) => {1235 return {1236 setHistory: (nextHistory) => {1237 set((state) => ({1238 history:1239 typeof nextHistory === 'function'1240 ? nextHistory(state.history)1241 : nextHistory,1242 }))1243 },1244 setCurrentMove: (nextCurrentMove) => {1245 set((state) => ({1246 currentMove:1247 typeof nextCurrentMove === 'function'1248 ? nextCurrentMove(state.currentMove)1249 : nextCurrentMove,1250 }))1251 },1252 setXIsNext: (nextXIsNext) => {1253 set((state) => ({1254 xIsNext:1255 typeof nextXIsNext === 'function'1256 ? nextXIsNext(state.xIsNext)1257 : nextXIsNext,1258 }))1259 },1260 }1261 },1262 ),1263)1264```12651266Next, update the `jumpTo` function inside `Game` component to update that `currentMove`. You’ll1267also set `xIsNext` to `true` if the number that you’re changing `currentMove` to is even.12681269```js {2-3}1270function jumpTo(nextMove) {1271 setCurrentMove(nextMove)1272 setXIsNext(currentMove % 2 === 0)1273}1274```12751276You will now make two changes to the `handlePlay` function in the `Game` component, which is called1277when you click on a square.12781279- If you "go back in time" and then make a new move from that point, you only want to keep the1280 history up to that point. Instead of adding `nextSquares` after all items in the history (using1281 the Array `.concat()` method), you'll add it after all items in1282 `history.slice(0, currentMove + 1)` to keep only that portion of the old history.1283- Each time a move is made, you need to update `currentMove` to point to the latest history entry.12841285```js {2-4}1286function handlePlay(nextSquares) {1287 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1288 setHistory(nextHistory)1289 setCurrentMove(nextHistory.length - 1)1290 setXIsNext(!xIsNext)1291}1292```12931294Finally, you will modify the `Game` component to render the currently selected move, instead of1295always rendering the final move:12961297```jsx {2-8}1298export default function Game() {1299 const history = useGameStore((state) => state.history)1300 const setHistory = useGameStore((state) => state.setHistory)1301 const currentMove = useGameStore((state) => state.currentMove)1302 const setCurrentMove = useGameStore((state) => state.setCurrentMove)1303 const xIsNext = useGameStore((state) => state.xIsNext)1304 const setXIsNext = useGameStore((state) => state.setXIsNext)1305 const currentSquares = history[currentMove]13061307 function handlePlay(nextSquares) {1308 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1309 setHistory(nextHistory)1310 setCurrentMove(nextHistory.length - 1)1311 setXIsNext(!xIsNext)1312 }13131314 function jumpTo(nextMove) {1315 setCurrentMove(nextMove)1316 setXIsNext(nextMove % 2 === 0)1317 }13181319 return (1320 <div1321 style={{1322 display: 'flex',1323 flexDirection: 'row',1324 fontFamily: 'monospace',1325 }}1326 >1327 <div>1328 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1329 </div>1330 <div style={{ marginLeft: '1rem' }}>1331 <ol>1332 {history.map((_, historyIndex) => {1333 const description =1334 historyIndex > 01335 ? `Go to move #${historyIndex}`1336 : 'Go to game start'13371338 return (1339 <li key={historyIndex}>1340 <button onClick={() => jumpTo(historyIndex)}>1341 {description}1342 </button>1343 </li>1344 )1345 })}1346 </ol>1347 </div>1348 </div>1349 )1350}1351```13521353### Final cleanup13541355If you look closely at the code, you'll see that `xIsNext` is `true` when `currentMove` is even and1356`false` when `currentMove` is odd. This means that if you know the value of `currentMove`, you can1357always determine what `xIsNext` should be.13581359There's no need to store `xIsNext` separately in the state. It’s better to avoid redundant state1360because it can reduce bugs and make your code easier to understand. Instead, you can calculate1361`xIsNext` based on `currentMove`:13621363```jsx {2-5,13,17}1364export default function Game() {1365 const history = useGameStore((state) => state.history)1366 const setHistory = useGameStore((state) => state.setHistory)1367 const currentMove = useGameStore((state) => state.currentMove)1368 const setCurrentMove = useGameStore((state) => state.setCurrentMove)1369 const xIsNext = currentMove % 2 === 01370 const currentSquares = history[currentMove]13711372 function handlePlay(nextSquares) {1373 const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1374 setHistory(nextHistory)1375 setCurrentMove(nextHistory.length - 1)1376 }13771378 function jumpTo(nextMove) {1379 setCurrentMove(nextMove)1380 }13811382 return (1383 <div1384 style={{1385 display: 'flex',1386 flexDirection: 'row',1387 fontFamily: 'monospace',1388 }}1389 >1390 <div>1391 <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1392 </div>1393 <div style={{ marginLeft: '1rem' }}>1394 <ol>1395 {history.map((_, historyIndex) => {1396 const description =1397 historyIndex > 01398 ? `Go to move #${historyIndex}`1399 : 'Go to game start'14001401 return (1402 <li key={historyIndex}>1403 <button onClick={() => jumpTo(historyIndex)}>1404 {description}1405 </button>1406 </li>1407 )1408 })}1409 </ol>1410 </div>1411 </div>1412 )1413}1414```14151416You no longer need the `xIsNext` state declaration or the calls to `setXIsNext`. Now, there’s no1417chance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding1418the components.14191420### Wrapping up14211422Congratulations! You’ve created a tic-tac-toe game that:14231424- Lets you play tic-tac-toe,1425- Indicates when a player has won the game or when is drawn,1426- Stores a game’s history as a game progresses,1427- Allows players to review a game’s history and see previous versions of a game’s board.14281429Nice work! We hope you now feel like you have a decent grasp of how React and Zustand works.
added:docs/learn/guides/updating-state.md+141 added
1---2title: Updating state3nav: 44---56## Flat updates78Updating state with Zustand is simple! Call the provided `set` function with9the new state, and it will be shallowly merged with the existing state in the10store. **Note** See next section for nested state.1112```tsx13import { create } from 'zustand'1415type State = {16 firstName: string17 lastName: string18}1920type Action = {21 updateFirstName: (firstName: State['firstName']) => void22 updateLastName: (lastName: State['lastName']) => void23}2425// Create your store, which includes both state and (optionally) actions26const usePersonStore = create<State & Action>((set) => ({27 firstName: '',28 lastName: '',29 updateFirstName: (firstName) => set(() => ({ firstName: firstName })),30 updateLastName: (lastName) => set(() => ({ lastName: lastName })),31}))3233// In consuming app34function App() {35 // "select" the needed state and actions, in this case, the firstName value36 // and the action updateFirstName37 const firstName = usePersonStore((state) => state.firstName)38 const updateFirstName = usePersonStore((state) => state.updateFirstName)3940 return (41 <main>42 <label>43 First name44 <input45 // Update the "firstName" state46 onChange={(e) => updateFirstName(e.currentTarget.value)}47 value={firstName}48 />49 </label>5051 <p>52 Hello, <strong>{firstName}!</strong>53 </p>54 </main>55 )56}57```5859## Deeply nested object6061If you have a deep state object like this:6263```ts64type State = {65 deep: {66 nested: {67 obj: { count: number }68 }69 }70}71```7273Updating nested state requires some effort to ensure the process is completed74immutably.7576### Normal approach7778Similar to React or Redux, the normal approach is to copy each level of the79state object. This is done with the spread operator `...`, and by manually80merging that in with the new state values. Like so:8182```ts83 normalInc: () =>84 set((state) => ({85 deep: {86 ...state.deep,87 nested: {88 ...state.deep.nested,89 obj: {90 ...state.deep.nested.obj,91 count: state.deep.nested.obj.count + 192 }93 }94 }95 })),96```9798This is very long! Let's explore some alternatives that will make your life99easier.100101### With Immer102103Many people use [Immer](https://github.com/immerjs/immer) to update nested104values. Immer can be used anytime you need to update nested state such as in105React, Redux and of course, Zustand!106107You can use Immer to shorten your state updates for deeply nested object. Let's108take a look at an example:109110```ts111 immerInc: () =>112 set(produce((state: State) => { ++state.deep.nested.obj.count })),113```114115What a reduction! Please take note of the [gotchas listed here](../../reference/integrations/immer-middleware.md).116117### With optics-ts118119There is another option with [optics-ts](https://github.com/akheron/optics-ts/):120121```ts122 opticsInc: () =>123 set(O.modify(O.optic<State>().path("deep.nested.obj.count"))((c) => c + 1)),124```125126Unlike Immer, optics-ts doesn't use proxies or mutation syntax.127128### With Ramda129130You can also use [Ramda](https://ramdajs.com/):131132```ts133 ramdaInc: () =>134 set(R.modifyPath(["deep", "nested", "obj", "count"], (c) => c + 1)),135```136137Both ramda and optics-ts also work with types.138139### Demo140141https://stackblitz.com/edit/vitejs-vite-j6bjdygu
added:docs/learn/index.md+54 added
1---2title: Learn3description: A guided path to understand Zustand fundamentals, common patterns, and when to reach for specific tools.4---56## Start here78If you are new to Zustand, begin here for installation, a high-level overview, and a hands-on tutorial.910- [Introduction](/learn/getting-started/introduction.md) — Install Zustand and create your first store.11- [Comparison with other tools](/learn/getting-started/comparison.md) — See how Zustand compares to Redux, Jotai, Recoil, and others.12- [Tutorial: Tic Tac Toe](/learn/guides/tutorial-tic-tac-toe.md) — Build a complete game to learn Zustand concepts step by step.1314## Core concepts1516The fundamentals of reading and updating state in a Zustand store.1718- [Updating state](/learn/guides/updating-state.md) — How to update primitive values, objects, and nested state.19- [Practice with no store actions](/learn/guides/practice-with-no-store-actions.md) — Define state updates outside the store for simpler patterns.20- [Slices pattern](/learn/guides/slices-pattern.md) — Split a large store into smaller, composable slices.21- [Immutable state and merging](/learn/guides/immutable-state-and-merging.md) — Understand how Zustand merges state and when to spread manually.22- [Maps and sets usage](/learn/guides/maps-and-sets-usage.md) — Work with `Map` and `Set` inside Zustand state correctly.2324## Performance and rendering2526Techniques for keeping re-renders minimal and components fast.2728- [Prevent rerenders with useShallow](/learn/guides/prevent-rerenders-with-use-shallow.md) — Use shallow comparison to avoid unnecessary re-renders when selecting objects.29- [Connect to state with URL hash](/learn/guides/connect-to-state-with-url-hash.md) — Sync store state with the URL hash for shareable UI state.30- [Event handler in pre React 18](/learn/guides/event-handler-in-pre-react-18.md) — Handle the batching edge case in React 17 and earlier.3132## TypeScript path3334Guides for typing stores, actions, and selectors with TypeScript.3536- [Beginner TypeScript](/learn/guides/beginner-typescript.md) — Type a basic store with state and actions.37- [Advanced TypeScript](/learn/guides/advanced-typescript.md) — Type slices, middleware stacks, and complex patterns.38- [Auto-generating selectors](/learn/guides/auto-generating-selectors.md) — Generate typed selectors automatically from a store definition.3940## Frameworks and platforms4142Using Zustand in server-rendered and framework-specific environments.4344- [Next.js](/learn/guides/nextjs.md) — Set up Zustand in a Next.js app with proper SSR handling.45- [SSR and hydration](/learn/guides/ssr-and-hydration.md) — Avoid hydration mismatches when rendering on the server.46- [Initialize state with props](/learn/guides/initialize-state-with-props.md) — Seed a store's initial state from React component props.4748## Testing and quality4950Best practices for writing reliable, maintainable code with Zustand.5152- [Testing stores and components](/learn/guides/testing.md) — Test store logic and React components that consume a store.53- [Flux-inspired practice](/learn/guides/flux-inspired-practice.md) — Apply Flux conventions to keep state changes predictable.54- [How to reset state](/learn/guides/how-to-reset-state.md) — Reset a store back to its initial state on demand.
deleted:docs/middlewares/combine.md-103 removed
1---2title: combine3description: How to create a store and get types automatically inferred4nav: 2015---67# combine89`combine` middleware lets you create a cohesive state by merging an initial state with a state10creator function that adds new state slices and actions. This is really helpful as it automatically11infers types, so there’s no need for explicit type definitions.1213> [!TIP]14> This makes state management more straightforward and efficient by making curried version of15> `create` and `createStore` not necessary for middleware usage.1617```js18const nextStateCreatorFn = combine(initialState, additionalStateCreatorFn)19```2021- [Types](#types)22 - [Signature](#combine-signature)23- [Reference](#reference)24- [Usage](#usage)25 - [Creating a state with inferred types](#creating-a-state-wit-inferred-types)26- [Troubleshooting](#troubleshooting)2728## Types2930### Signature3132```ts33combine<T, U>(initialState: T, additionalStateCreatorFn: StateCreator<T, [], [], U>): StateCreator<Omit<T, keyof U> & U, [], []>34```3536## Reference3738### `combine(initialState, additionalStateCreatorFn)`3940#### Parameters4142- `initialState`: The value you want the state to be initially. It can be a value of any type,43 except a function.44- `additionalStateCreatorFn`: A function that takes `set` function, `get` function and `store` as45 arguments. Usually, you will return an object with the methods you want to expose.4647#### Returns4849`combine` returns a state creator function.5051## Usage5253### Creating a store with inferred types5455This example shows you how you can create a store and get types automatically inferred, so you56don’t need to define them explicitly.5758```ts59import { createStore } from 'zustand/vanilla'60import { combine } from 'zustand/middleware'6162const positionStore = createStore(63 combine({ position: { x: 0, y: 0 } }, (set) => ({64 setPosition: (position) => set({ position }),65 })),66)6768const $dotContainer = document.getElementById('dot-container') as HTMLDivElement69const $dot = document.getElementById('dot') as HTMLDivElement7071$dotContainer.addEventListener('pointermove', (event) => {72 positionStore.getState().setPosition({73 x: event.clientX,74 y: event.clientY,75 })76})7778const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {79 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`80}8182render(positionStore.getInitialState(), positionStore.getInitialState())8384positionStore.subscribe(render)85```8687Here's the `html` code8889```html90<div91 id="dot-container"92 style="position: relative; width: 100vw; height: 100vh;"93>94 <div95 id="dot"96 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"97 ></div>98</div>99```100101## Troubleshooting102103TBD
deleted:docs/middlewares/devtools.md-352 removed
1---2title: devtools3description: How to time-travel debug your store4nav: 2055---67# devtools89`devtools` middleware lets you use [Redux DevTools Extension](https://github.com/reduxjs/redux-devtools)10without Redux. Read more about the benefits of using [Redux DevTools for debugging](https://redux.js.org/style-guide/#use-the-redux-devtools-extension-for-debugging).1112> [!IMPORTANT]13> In order to use `devtools` from `zustand/middleware` you need to install14> `@redux-devtools/extension` library.1516```js17const nextStateCreatorFn = devtools(stateCreatorFn, devtoolsOptions)18```1920- [Types](#types)21 - [Signature](#signature)22 - [Mutator](#mutator)23- [Reference](#reference)24- [Usage](#usage)25 - [Debugging a store](#debugging-a-store)26 - [Debugging a Slices pattern based store](#debugging-a-slices-pattern-based-store)27 - [Filtering actions with actionsDenylist](#filtering-actions-with-actionsdenylist)28 - [Cleanup](#cleanup)29- [Troubleshooting](#troubleshooting)30 - [Only one store is displayed](#only-one-store-is-displayed)31 - [Action names are labeled as 'anonymous'](#all-action-names-are-labeled-as-anonymous)3233## Types3435### Signature3637```ts38devtools<T>(stateCreatorFn: StateCreator<T, [], []>, devtoolsOptions?: DevtoolsOptions): StateCreator<T, [['zustand/devtools', never]], []>39```4041### Mutator4243<!-- prettier-ignore-start -->44```ts45['zustand/devtools', never]46```47<!-- prettier-ignore-end -->4849## Reference5051### `devtools(stateCreatorFn, devtoolsOptions)`5253#### Parameters5455- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.56 Usually, you will return an object with the methods you want to expose.57- **optional** `devtoolsOptions`: An object to define `Redux Devtools` options.58 - **optional** `name`: A custom identifier for the connection in the Redux DevTools.59 - **optional** `enabled`: Defaults to `true` when is on development mode, and defaults to `false`60 when is on production mode. Enables or disables the Redux DevTools integration61 for this store.62 - **optional** `anonymousActionType`: Defaults to the inferred action type or `anonymous` if63 unavailable. A string to use as the action type for anonymous mutations in the Redux DevTools.64 - **optional** `store`: A custom identifier for the store in the Redux DevTools.65 - **optional** `actionsDenylist`: A string or array of strings (regex patterns) that specify which66 actions should be filtered out from Redux DevTools. This option is passed directly to Redux DevTools67 for filtering. For example, `['secret.*']` will filter out all actions starting with "secret".6869#### Returns7071`devtools` returns a state creator function.7273## Usage7475### Debugging a store7677This example shows you how you can use `Redux Devtools` to debug a store7879```ts80import { create, StateCreator } from 'zustand'81import { devtools } from 'zustand/middleware'8283type JungleStore = {84 bears: number85 addBear: () => void86 fishes: number87 addFish: () => void88}8990const useJungleStore = create<JungleStore>()(91 devtools((set) => ({92 bears: 0,93 addBear: () =>94 set((state) => ({ bears: state.bears + 1 }), undefined, 'jungle/addBear'),95 fishes: 0,96 addFish: () =>97 set(98 (state) => ({ fishes: state.fishes + 1 }),99 undefined,100 'jungle/addFish',101 ),102 })),103)104```105106### Debugging a Slices pattern based store107108This example shows you how you can use `Redux Devtools` to debug a Slices pattern based store109110```ts111import { create, StateCreator } from 'zustand'112import { devtools } from 'zustand/middleware'113114type BearSlice = {115 bears: number116 addBear: () => void117}118119type FishSlice = {120 fishes: number121 addFish: () => void122}123124type JungleStore = BearSlice & FishSlice125126const createBearSlice: StateCreator<127 JungleStore,128 [['zustand/devtools', never]],129 [],130 BearSlice131> = (set) => ({132 bears: 0,133 addBear: () =>134 set(135 (state) => ({ bears: state.bears + 1 }),136 undefined,137 'jungle:bear/addBear',138 ),139})140141const createFishSlice: StateCreator<142 JungleStore,143 [['zustand/devtools', never]],144 [],145 FishSlice146> = (set) => ({147 fishes: 0,148 addFish: () =>149 set(150 (state) => ({ fishes: state.fishes + 1 }),151 undefined,152 'jungle:fish/addFish',153 ),154})155156const useJungleStore = create<JungleStore>()(157 devtools((...args) => ({158 ...createBearSlice(...args),159 ...createFishSlice(...args),160 })),161)162```163164### Filtering actions with actionsDenylist165166You can filter out specific actions from Redux DevTools using the `actionsDenylist` option. This is useful for hiding internal or sensitive actions from the DevTools timeline.167168```ts169import { create } from 'zustand'170import { devtools } from 'zustand/middleware'171172type Store = {173 user: string | null174 token: string | null175 login: (user: string, token: string) => void176 logout: () => void177 updateData: () => void178}179180const useStore = create<Store>()(181 devtools(182 (set) => ({183 user: null,184 token: null,185 login: (user, token) => set({ user, token }, undefined, 'auth/login'),186 logout: () => set({ user: null, token: null }, undefined, 'auth/logout'),187 updateData: () =>188 set({ user: 'updated' }, undefined, 'internal/updateData'),189 }),190 {191 name: 'AuthStore',192 // Filter out actions matching these regex patterns193 actionsDenylist: ['internal/.*'], // Hides all 'internal/*' actions194 },195 ),196)197```198199You can also use a single regex string:200201```ts202const useStore = create<Store>()(203 devtools(204 (set) => ({205 // ... state and actions206 }),207 {208 name: 'MyStore',209 actionsDenylist: 'secret.*', // Hides all actions starting with 'secret'210 },211 ),212)213```214215> [!NOTE]216> The `actionsDenylist` option uses regex pattern matching and is handled directly by Redux DevTools Extension.217> All actions are still sent to DevTools, but matching actions are filtered from the display.218219### Cleanup220221When a store is no longer needed, you can clean up the Redux DevTools connection by calling the `cleanup` method on the store:222223```ts224import { create } from 'zustand'225import { devtools } from 'zustand/middleware'226227const useStore = create(228 devtools((set) => ({229 count: 0,230 increment: () => set((state) => ({ count: state.count + 1 })),231 })),232)233234// When you're done with the store, clean it up235useStore.devtools.cleanup()236```237238This is particularly useful in applications that wrap store in context or create multiple stores dynamically.239240## Troubleshooting241242### Only one store is displayed243244By default, `Redux Devtools` only show one store at a time, so in order to see other stores you245need to use store selector and choose a different store.246247### All action names are labeled as 'anonymous'248249If an action type name is not provided, it is defaulted to "anonymous". You can customize this250default value by providing a `anonymousActionType` parameter:251252For instance the next example doesn't have action type name:253254```ts255import { create, StateCreator } from 'zustand'256import { devtools } from 'zustand/middleware'257258type BearSlice = {259 bears: number260 addBear: () => void261}262263type FishSlice = {264 fishes: number265 addFish: () => void266}267268type JungleStore = BearSlice & FishSlice269270const createBearSlice: StateCreator<271 JungleStore,272 [['zustand/devtools', never]],273 [],274 BearSlice275> = (set) => ({276 bears: 0,277 addBear: () => set((state) => ({ bears: state.bears + 1 })),278 eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),279})280281const createFishSlice: StateCreator<282 JungleStore,283 [['zustand/devtools', never]],284 [],285 FishSlice286> = (set) => ({287 fishes: 0,288 addFish: () => set((state) => ({ fishes: state.fishes + 1 })),289})290291const useJungleStore = create<JungleStore>()(292 devtools((...args) => ({293 ...createBearSlice(...args),294 ...createFishSlice(...args),295 })),296)297```298299In order to fix the previous example, we need to provide an action type name as the third parameter.300Additionally, to preserve the default behavior of the replacement logic, the second parameter301should be set to `undefined`.302303Here's the fixed previous example304305```ts306import { create, StateCreator } from 'zustand'307308type BearSlice = {309 bears: number310 addBear: () => void311}312313type FishSlice = {314 fishes: number315 addFish: () => void316}317318type JungleStore = BearSlice & FishSlice319320const createBearSlice: StateCreator<321 JungleStore,322 [['zustand/devtools', never]],323 [],324 BearSlice325> = (set) => ({326 bears: 0,327 addBear: () =>328 set((state) => ({ bears: state.bears + 1 }), undefined, 'bear/addBear'),329})330331const createFishSlice: StateCreator<332 JungleStore,333 [['zustand/devtools', never]],334 [],335 FishSlice336> = (set) => ({337 fishes: 0,338 addFish: () =>339 set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fish/addFish'),340})341342const useJungleStore = create<JungleStore>()(343 devtools((...args) => ({344 ...createBearSlice(...args),345 ...createFishSlice(...args),346 })),347)348```349350> [!IMPORTANT]351> Do not set the second parameter to `true` or `false` unless you want to override the default352> replacement logic
deleted:docs/middlewares/immer.md-239 removed
1---2title: immer3description: How to perform immutable updates in a store without boilerplate code4nav: 2065---67# immer89`immer` middleware lets you perform immutable updates.1011> [!IMPORTANT]12> In order to use `immer` from `zustand/middleware/immer` you need to install13> `immer` library.1415```js16const nextStateCreatorFn = immer(stateCreatorFn)17```1819- [Types](#types)20 - [Signature](#signature)21 - [Mutator](#mutator)22- [Reference](#reference)23- [Usage](#usage)24- [Troubleshooting](#troubleshooting)2526## Types2728### Signature2930```ts31immer<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/immer', never]], []>32```3334### Mutator3536<!-- prettier-ignore-start -->37```ts38['zustand/immer', never]39```40<!-- prettier-ignore-end -->4142## Reference4344### `immer(stateCreatorFn)`4546#### Parameters4748- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.49 Usually, you will return an object with the methods you want to expose.5051#### Returns5253`immer` returns a state creator function.5455## Usage5657### Updating state without boilerplate code5859In the next example, we're going to update the `person` object. Since it's a nested object, we need60to create a copy of the entire object before making the update.6162```ts63import { createStore } from 'zustand/vanilla'6465type PersonStoreState = {66 person: { firstName: string; lastName: string; email: string }67}6869type PersonStoreActions = {70 setPerson: (71 nextPerson: (72 person: PersonStoreState['person'],73 ) => PersonStoreState['person'] | PersonStoreState['person'],74 ) => void75}7677type PersonStore = PersonStoreState & PersonStoreActions7879const personStore = createStore<PersonStore>()((set) => ({80 person: {81 firstName: 'Barbara',82 lastName: 'Hepworth',83 email: 'bhepworth@sculpture.com',84 },85 setPerson: (nextPerson) =>86 set((state) => ({87 person:88 typeof nextPerson === 'function'89 ? nextPerson(state.person)90 : nextPerson,91 })),92}))9394const $firstNameInput = document.getElementById(95 'first-name',96) as HTMLInputElement97const $lastNameInput = document.getElementById('last-name') as HTMLInputElement98const $emailInput = document.getElementById('email') as HTMLInputElement99const $result = document.getElementById('result') as HTMLDivElement100101function handleFirstNameChange(event: Event) {102 personStore.getState().setPerson((person) => ({103 ...person,104 firstName: (event.target as any).value,105 }))106}107108function handleLastNameChange(event: Event) {109 personStore.getState().setPerson((person) => ({110 ...person,111 lastName: (event.target as any).value,112 }))113}114115function handleEmailChange(event: Event) {116 personStore.getState().setPerson((person) => ({117 ...person,118 email: (event.target as any).value,119 }))120}121122$firstNameInput.addEventListener('input', handleFirstNameChange)123$lastNameInput.addEventListener('input', handleLastNameChange)124$emailInput.addEventListener('input', handleEmailChange)125126const render: Parameters<typeof personStore.subscribe>[0] = (state) => {127 $firstNameInput.value = state.person.firstName128 $lastNameInput.value = state.person.lastName129 $emailInput.value = state.person.email130131 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`132}133134render(personStore.getInitialState(), personStore.getInitialState())135136personStore.subscribe(render)137```138139Here's the `html` code140141```html142<label style="display: block">143 First name:144 <input id="first-name" />145</label>146<label style="display: block">147 Last name:148 <input id="last-name" />149</label>150<label style="display: block">151 Email:152 <input id="email" />153</label>154<p id="result"></p>155```156157To avoid manually copying the entire object before making updates, we'll use the `immer`158middleware.159160```ts161import { createStore } from 'zustand/vanilla'162import { immer } from 'zustand/middleware/immer'163164type PersonStoreState = {165 person: { firstName: string; lastName: string; email: string }166}167168type PersonStoreActions = {169 setPerson: (170 nextPerson: (171 person: PersonStoreState['person'],172 ) => PersonStoreState['person'] | PersonStoreState['person'],173 ) => void174}175176type PersonStore = PersonStoreState & PersonStoreActions177178const personStore = createStore<PersonStore>()(179 immer((set) => ({180 person: {181 firstName: 'Barbara',182 lastName: 'Hepworth',183 email: 'bhepworth@sculpture.com',184 },185 setPerson: (nextPerson) =>186 set((state) => {187 state.person =188 typeof nextPerson === 'function'189 ? nextPerson(state.person)190 : nextPerson191 }),192 })),193)194195const $firstNameInput = document.getElementById(196 'first-name',197) as HTMLInputElement198const $lastNameInput = document.getElementById('last-name') as HTMLInputElement199const $emailInput = document.getElementById('email') as HTMLInputElement200const $result = document.getElementById('result') as HTMLDivElement201202function handleFirstNameChange(event: Event) {203 personStore.getState().setPerson((person) => {204 person.firstName = (event.target as any).value205 })206}207208function handleLastNameChange(event: Event) {209 personStore.getState().setPerson((person) => {210 person.lastName = (event.target as any).value211 })212}213214function handleEmailChange(event: Event) {215 personStore.getState().setPerson((person) => {216 person.email = (event.target as any).value217 })218}219220$firstNameInput.addEventListener('input', handleFirstNameChange)221$lastNameInput.addEventListener('input', handleLastNameChange)222$emailInput.addEventListener('input', handleEmailChange)223224const render: Parameters<typeof personStore.subscribe>[0] = (state) => {225 $firstNameInput.value = state.person.firstName226 $lastNameInput.value = state.person.lastName227 $emailInput.value = state.person.email228229 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`230}231232render(personStore.getInitialState(), personStore.getInitialState())233234personStore.subscribe(render)235```236237## Troubleshooting238239TBD
deleted:docs/middlewares/persist.md-988 removed
1---2title: persist3description: How to persist a store4nav: 2075---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```ts34persist<T, U>(stateCreatorFn: StateCreator<T, [], []>, persistOptions?: PersistOptions<T, U>): StateCreator<T, [['zustand/persist', U]], []>35```3637### Mutator3839<!-- prettier-ignore-start -->40```ts41['zustand/persist', U]42```43<!-- prettier-ignore-end -->4445## Reference4647### `persist(stateCreatorFn)`4849#### Parameters5051- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.52 Usually, you will return an object with the methods you want to expose.53- `persistOptions`: An object to define storage options.54 - `name`: A unique name of the item for your store in the storage.55 - **optional** `storage`: Defaults to `createJSONStorage(() => localStorage)`.56 - **optional** `partialize`: A function to filter state fields before persisting it.57 - **optional** `onRehydrateStorage`: A function or function returning a function that allows58 custom logic before and after state rehydration.59 - **optional** `version`: A version number for the persisted state. If the stored state version60 doesn't match, it won't be used.61 - **optional** `migrate`: A function to migrate persisted state if the version mismatch occurs.62 - **optional** `merge`: A function for custom logic when merging persisted state with the current63 state during rehydration. Defaults to a shallow merge.64 - **optional** `skipHydration`: Defaults to `false`. If `true`, the middleware won't65 automatically rehydrate the state on initialization. Use `rehydrate` function manually in this66 case. This is useful for server-side rendering (SSR) applications.6768#### Returns6970`persist` returns a state creator function.7172## Usage7374### Persisting a state7576In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`77middleware. The example tracks the `position` of the mouse as it moves within a container and78stores the `position` in local storage, so it persists even when the page reloads.7980We start by setting up a vanilla store that holds the position (an object with `x` and `y`81coordinates) and an action to update it. We'll also use the `persist` middleware to store the82position in `localStorage`.8384```ts85import { createStore } from 'zustand/vanilla'86import { persist } from 'zustand/middleware'8788type PositionStoreState = { position: { x: number; y: number } }8990type PositionStoreActions = {91 setPosition: (nextPosition: PositionStoreState['position']) => void92}9394type PositionStore = PositionStoreState & PositionStoreActions9596const positionStore = createStore<PositionStore>()(97 persist(98 (set) => ({99 position: { x: 0, y: 0 },100 setPosition: (position) => set({ position }),101 }),102 { name: 'position-storage' },103 ),104)105```106107Next, we'll track the mouse movements inside a div and update the store with the new position.108109```ts110const $dotContainer = document.getElementById('dot-container') as HTMLDivElement111const $dot = document.getElementById('dot') as HTMLDivElement112113$dotContainer.addEventListener('pointermove', (event) => {114 positionStore.getState().setPosition({115 x: event.clientX,116 y: event.clientY,117 })118})119```120121We want to reflect the position updates on the screen by moving a div element122(representing the dot) to the new coordinates.123124```ts125const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {126 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`127}128129render(positionStore.getState(), positionStore.getState())130131positionStore.subscribe(render)132```133134Here’s the complete code.135136```ts137import { createStore } from 'zustand/vanilla'138import { persist } from 'zustand/middleware'139140type PositionStoreState = { position: { x: number; y: number } }141142type PositionStoreActions = {143 setPosition: (nextPosition: PositionStoreState['position']) => void144}145146type PositionStore = PositionStoreState & PositionStoreActions147148const positionStore = createStore<PositionStore>()(149 persist(150 (set) => ({151 position: { x: 0, y: 0 },152 setPosition: (position) => set({ position }),153 }),154 { name: 'position-storage' },155 ),156)157158const $dotContainer = document.getElementById('dot-container') as HTMLDivElement159const $dot = document.getElementById('dot') as HTMLDivElement160161$dotContainer.addEventListener('pointermove', (event) => {162 positionStore.getState().setPosition({163 x: event.clientX,164 y: event.clientY,165 })166})167168const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {169 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`170}171172render(positionStore.getState(), positionStore.getState())173174positionStore.subscribe(render)175```176177Here's the `html` code178179```html180<div181 id="dot-container"182 style="position: relative; width: 100vw; height: 100vh;"183>184 <div185 id="dot"186 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"187 ></div>188</div>189```190191### Persisting a state partially192193In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`194middleware. Additionally, we'll show you how to persist only part of the state195(partial persistence), which can be useful when you don’t want to store the entire state in196`localStorage`.197198We’ll first create a vanilla store that holds the position state and actions to update it. We'll199use the `persist` middleware to persist only the relevant part of the state (in this case, the200context containing the position).201202```ts203import { createStore } from 'zustand/vanilla'204import { persist } from 'zustand/middleware'205206type PositionStoreState = {207 context: {208 position: { x: number; y: number }209 }210}211212type PositionStoreActions = {213 actions: {214 setPosition: (215 nextPosition: PositionStoreState['context']['position'],216 ) => void217 }218}219220type PositionStore = PositionStoreState & PositionStoreActions221222const positionStore = createStore<PositionStore>()(223 persist(224 (set) => ({225 context: {226 position: { x: 0, y: 0 },227 },228 actions: {229 setPosition: (position) => set({ context: { position } }),230 },231 }),232 {233 name: 'position-storage',234 partialize: (state) => ({ context: state.context }),235 },236 ),237)238```239240Next, we'll track the mouse movements inside a div and update the store with the new position.241242```ts243const $dotContainer = document.getElementById('dot-container') as HTMLDivElement244const $dot = document.getElementById('dot') as HTMLDivElement245246$dotContainer.addEventListener('pointermove', (event) => {247 positionStore.getState().actions.setPosition({248 x: event.clientX,249 y: event.clientY,250 })251})252```253254We want to reflect the position updates on the screen by moving a div element255(representing the dot) to the new coordinates.256257```ts258const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {259 $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`260}261262render(positionStore.getState(), positionStore.getState())263264positionStore.subscribe(render)265```266267Here’s the full code to create a dot that follows your mouse movement inside a container and268persists the `context` in `localStorage`.269270```ts271import { createStore } from 'zustand/vanilla'272import { persist } from 'zustand/middleware'273274type PositionStoreState = {275 context: {276 position: { x: number; y: number }277 }278}279280type PositionStoreActions = {281 actions: {282 setPosition: (283 nextPosition: PositionStoreState['context']['position'],284 ) => void285 }286}287288type PositionStore = PositionStoreState & PositionStoreActions289290const positionStore = createStore<PositionStore>()(291 persist(292 (set) => ({293 context: {294 position: { x: 0, y: 0 },295 },296 actions: {297 setPosition: (position) => set({ context: { position } }),298 },299 }),300 {301 name: 'position-storage',302 partialize: (state) => ({ context: state.context }),303 },304 ),305)306307const $dotContainer = document.getElementById('dot-container') as HTMLDivElement308const $dot = document.getElementById('dot') as HTMLDivElement309310$dotContainer.addEventListener('pointermove', (event) => {311 positionStore.getState().actions.setPosition({312 x: event.clientX,313 y: event.clientY,314 })315})316317const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {318 $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`319}320321render(positionStore.getState(), positionStore.getState())322323positionStore.subscribe(render)324```325326Here's the `html` code327328```html329<div330 id="dot-container"331 style="position: relative; width: 100vw; height: 100vh;"332>333 <div334 id="dot"335 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"336 ></div>337</div>338```339340### Persisting a state with custom storage341342In this mini tutorial, we’ll create a simple position-tracking system using vanilla store, where343the position state is persisted in the URL's search parameters. This approach allows state344persistence directly in the browser's URL, which can be useful for maintaining state across page345reloads or sharing links with state embedded.346347We need to implement functions to manipulate URL search parameters as if they were a storage348mechanism. This includes retrieving, setting, and removing parameters.349350```ts351const getSearchParams = () => {352 return new URL(location.href).searchParams353}354355const updateSearchParams = (searchParams: URLSearchParams) => {356 window.history.replaceState(357 {},358 '',359 `${location.pathname}?${searchParams.toString()}`,360 )361}362363const getSearchParam = (key: string) => {364 const searchParams = getSearchParams()365 return searchParams.get(key)366}367368const updateSearchParam = (key: string, value: string) => {369 const searchParams = getSearchParams()370 searchParams.set(key, value)371372 updateSearchParams(searchParams)373}374375const removeSearchParam = (key: string) => {376 const searchParams = getSearchParams()377 searchParams.delete(key)378379 updateSearchParams(searchParams)380}381```382383To use the URL search parameters as storage, we define a `searchParamsStorage` object with384`getItem`, `setItem`, and `removeItem` methods. These methods map to our custom functions that385manipulate search parameters.386387```ts388const searchParamsStorage = {389 getItem: (key: string) => getSearchParam(key),390 setItem: (key: string, value: string) => updateSearchParam(key, value),391 removeItem: (key: string) => removeSearchParam(key),392}393```394395Now, we initialize the vanilla store using the `persist` middleware, specifying that we want to use396our custom storage. Instead of the default `localStorage` or `sessionStorage`, we’ll persist the397position data in the URL search parameters.398399```ts400import { createStore } from 'zustand/vanilla'401import { persist, createJSONStorage } from 'zustand/middleware'402403type PositionStoreState = { position: { x: number; y: number } }404405type PositionStoreActions = {406 setPosition: (nextPosition: PositionStoreState['position']) => void407}408409type PositionStore = PositionStoreState & PositionStoreActions410411const positionStore = createStore<PositionStore>()(412 persist(413 (set) => ({414 position: { x: 0, y: 0 },415 setPosition: (position) => set({ position }),416 }),417 {418 name: 'position-storage',419 storage: createJSONStorage(() => searchParamsStorage),420 },421 ),422)423```424425Next, we'll track the mouse movements inside a div and update the store with the new position.426427```ts428const $dotContainer = document.getElementById('dot-container') as HTMLDivElement429const $dot = document.getElementById('dot') as HTMLDivElement430431$dotContainer.addEventListener('pointermove', (event) => {432 positionStore.getState().setPosition({433 x: event.clientX,434 y: event.clientY,435 })436})437```438439We want to reflect the position updates on the screen by moving a div element440(representing the dot) to the new coordinates.441442```ts443const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {444 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`445}446447render(positionStore.getState(), positionStore.getState())448449positionStore.subscribe(render)450```451452Here’s the full code to create a dot that follows your mouse movement inside a container and453persists the position in URL's search parameters.454455```ts456import { createStore } from 'zustand/vanilla'457import { persist, createJSONStorage } from 'zustand/middleware'458459type PositionStoreState = { position: { x: number; y: number } }460461type PositionStoreActions = {462 setPosition: (nextPosition: PositionStoreState['position']) => void463}464465type PositionStore = PositionStoreState & PositionStoreActions466467const getSearchParams = () => {468 return new URL(location.href).searchParams469}470471const updateSearchParams = (searchParams: URLSearchParams) => {472 window.history.replaceState(473 {},474 '',475 `${location.pathname}?${searchParams.toString()}`,476 )477}478479const getSearchParam = (key: string) => {480 const searchParams = getSearchParams()481 return searchParams.get(key)482}483484const updateSearchParam = (key: string, value: string) => {485 const searchParams = getSearchParams()486 searchParams.set(key, value)487488 updateSearchParams(searchParams)489}490491const removeSearchParam = (key: string) => {492 const searchParams = getSearchParams()493 searchParams.delete(key)494495 updateSearchParams(searchParams)496}497498const searchParamsStorage = {499 getItem: (key: string) => getSearchParam(key),500 setItem: (key: string, value: string) => updateSearchParam(key, value),501 removeItem: (key: string) => removeSearchParam(key),502}503504const positionStore = createStore<PositionStore>()(505 persist(506 (set) => ({507 position: { x: 0, y: 0 },508 setPosition: (position) => set({ position }),509 }),510 {511 name: 'position-storage',512 storage: createJSONStorage(() => searchParamsStorage),513 },514 ),515)516517const $dotContainer = document.getElementById('dot-container') as HTMLDivElement518const $dot = document.getElementById('dot') as HTMLDivElement519520$dotContainer.addEventListener('pointermove', (event) => {521 positionStore.getState().setPosition({522 x: event.clientX,523 y: event.clientY,524 })525})526527const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {528 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`529}530531render(positionStore.getState(), positionStore.getState())532533positionStore.subscribe(render)534```535536Here's the `html` code537538```html539<div540 id="dot-container"541 style="position: relative; width: 100vw; height: 100vh;"542>543 <div544 id="dot"545 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"546 ></div>547</div>548```549550### Persisting a state through versioning and migrations551552In this tutorial, we’ll explore how to manage state persistence using versioning and migration.553We will demonstrate how to evolve your state schema across versions without breaking existing554persisted data.555556Before moving to versioned state management, we simulate an initial state for `version` 0. This is557done by manually setting a `version` 0 state in `localStorage` if it doesn't already exist. The558`version` 0 state saves the coordinates as `x` and `y` fields.559560```ts561// For tutorial purposes only562if (!localStorage.getItem('position-storage')) {563 localStorage.setItem(564 'position-storage',565 JSON.stringify({566 state: { x: 100, y: 100 }, // version 0 structure567 version: 0,568 }),569 )570}571```572573Next, we use `persist` middleware to handle state persistence. We also add a migration function to574handle changes between versions. In this example, we `migrate` the state from `version` 0 (where575`x` and `y` are separate) to `version` 1, where they are combined into a `position` object.576577```ts578migrate: (persisted: any, version) => {579 if (version === 0) {580 persisted.position = { x: persisted.x, y: persisted.y }581 delete persisted.x582 delete persisted.y583 }584585 return persisted586}587```588589Next, we'll track the mouse movements inside a div and update the store with the new position.590591```ts592const $dotContainer = document.getElementById('dot-container') as HTMLDivElement593const $dot = document.getElementById('dot') as HTMLDivElement594595$dotContainer.addEventListener('pointermove', (event) => {596 positionStore.getState().setPosition({597 x: event.clientX,598 y: event.clientY,599 })600})601```602603We want to reflect the position updates on the screen by moving a div element604(representing the dot) to the new coordinates.605606```ts607const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {608 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`609}610611render(positionStore.getState(), positionStore.getState())612613positionStore.subscribe(render)614```615616Here’s the complete code.617618```ts619import { createStore } from 'zustand/vanilla'620import { persist } from 'zustand/middleware'621622// For tutorial purposes only623if (!localStorage.getItem('position-storage')) {624 localStorage.setItem(625 'position-storage',626 JSON.stringify({627 state: { x: 100, y: 100 },628 version: 0,629 }),630 )631}632633type PositionStoreState = { position: { x: number; y: number } }634635type PositionStoreActions = {636 setPosition: (nextPosition: PositionStoreState['position']) => void637}638639type PositionStore = PositionStoreState & PositionStoreActions640641const positionStore = createStore<PositionStore>()(642 persist(643 (set) => ({644 position: { x: 0, y: 0 }, // version 0: just x: 0, y: 0645 setPosition: (position) => set({ position }),646 }),647 {648 name: 'position-storage',649 version: 1,650 migrate: (persisted: any, version) => {651 if (version === 0) {652 persisted.position = { x: persisted.x, y: persisted.y }653 delete persisted.x654 delete persisted.y655 }656657 return persisted658 },659 },660 ),661)662663const $dotContainer = document.getElementById('dot-container') as HTMLDivElement664const $dot = document.getElementById('dot') as HTMLDivElement665666$dotContainer.addEventListener('pointermove', (event) => {667 positionStore.getState().setPosition({668 x: event.clientX,669 y: event.clientY,670 })671})672673const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {674 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`675}676677render(positionStore.getState(), positionStore.getState())678679positionStore.subscribe(render)680```681682Here's the `html` code683684```html685<div686 id="dot-container"687 style="position: relative; width: 100vw; height: 100vh;"688>689 <div690 id="dot"691 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"692 ></div>693</div>694```695696### Persisting a state with nested objects697698In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`699and `y` coordinates. We will also implement persistence using `localStorage` and demonstrate how to700handle merging of state with potentially missing fields.701702To simulate an initial state for the tutorial, we will check if our position data exists in703`localStorage`. If it doesn't, we’ll set it up.704705```ts706if (!localStorage.getItem('position-storage')) {707 localStorage.setItem(708 'position-storage',709 JSON.stringify({710 state: { position: { y: 100 } }, // missing `x` field711 version: 0,712 }),713 )714}715```716717Now, we will create the store and configure it to use persistence and deep merging.718719```ts720import { createStore } from 'zustand/vanilla'721import { persist } from 'zustand/middleware'722import createDeepMerge from '@fastify/deepmerge'723724const deepMerge = createDeepMerge({ all: true })725726type PositionStoreState = { position: { x: number; y: number } }727728type PositionStoreActions = {729 setPosition: (nextPosition: PositionStoreState['position']) => void730}731732type PositionStore = PositionStoreState & PositionStoreActions733734const positionStore = createStore<PositionStore>()(735 persist(736 (set) => ({737 position: { x: 0, y: 0 },738 setPosition: (position) => set({ position }),739 }),740 {741 name: 'position-storage',742 merge: (persisted, current) => deepMerge(current, persisted) as never,743 },744 ),745)746```747748Next, we'll track the mouse movements inside a div and update the store with the new position.749750```ts751const $dotContainer = document.getElementById('dot-container') as HTMLDivElement752const $dot = document.getElementById('dot') as HTMLDivElement753754$dotContainer.addEventListener('pointermove', (event) => {755 positionStore.getState().setPosition({756 x: event.clientX,757 y: event.clientY,758 })759})760```761762We want to reflect the position updates on the screen by moving a div element763(representing the dot) to the new coordinates.764765```ts766const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {767 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`768}769770render(positionStore.getState(), positionStore.getState())771772positionStore.subscribe(render)773```774775Here’s the complete code.776777```ts778import { createStore } from 'zustand/vanilla'779import { persist } from 'zustand/middleware'780import createDeepMerge from '@fastify/deepmerge'781782const deepMerge = createDeepMerge({ all: true })783784// For tutorial purposes only785if (!localStorage.getItem('position-storage')) {786 localStorage.setItem(787 'position-storage',788 JSON.stringify({789 state: { position: { y: 100 } }, // missing `x` field790 version: 0,791 }),792 )793}794795type PositionStoreState = { position: { x: number; y: number } }796797type PositionStoreActions = {798 setPosition: (nextPosition: PositionStoreState['position']) => void799}800801type PositionStore = PositionStoreState & PositionStoreActions802803const positionStore = createStore<PositionStore>()(804 persist(805 (set) => ({806 position: { x: 0, y: 0 },807 setPosition: (position) => set({ position }),808 }),809 {810 name: 'position-storage',811 merge: (persisted, current) => deepMerge(current, persisted) as never,812 },813 ),814)815816const $dotContainer = document.getElementById('dot-container') as HTMLDivElement817const $dot = document.getElementById('dot') as HTMLDivElement818819$dotContainer.addEventListener('pointermove', (event) => {820 positionStore.getState().setPosition({821 x: event.clientX,822 y: event.clientY,823 })824})825826const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {827 console.log({ state })828 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`829}830831render(positionStore.getState(), positionStore.getState())832833positionStore.subscribe(render)834```835836Here's the `html` code837838```html839<div840 id="dot-container"841 style="position: relative; width: 100vw; height: 100vh;"842>843 <div844 id="dot"845 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"846 ></div>847</div>848```849850### Persisting a state and hydrate it manually851852In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`853and `y` coordinates. We will also implement persistence using `localStorage` and explore how to854skip the hydration process and manually trigger rehydration after a delay.855856We start by setting up a vanilla store that holds the position (an object with `x` and `y`857coordinates) and an action to update it. Furthermore, we'll also use the `persist` middleware to858store the position in `localStorage` but skipping hydration.859860```ts861import { createStore } from 'zustand/vanilla'862import { persist } from 'zustand/middleware'863864type PositionStoreState = { position: { x: number; y: number } }865866type PositionStoreActions = {867 setPosition: (nextPosition: PositionStoreState['position']) => void868}869870type PositionStore = PositionStoreState & PositionStoreActions871872const positionStore = createStore<PositionStore>()(873 persist(874 (set) => ({875 position: { x: 0, y: 0 },876 setPosition: (position) => set({ position }),877 }),878 {879 name: 'position-storage',880 skipHydration: true,881 },882 ),883)884```885886Since we skipped hydration in the initial setup, we will manually rehydrate the state. Here, we’re887using `setTimeout` to simulate a delayed rehydration.888889```ts890setTimeout(() => {891 positionStore.persist.rehydrate()892}, 2000)893```894895Next, we'll track the mouse movements inside a div and update the store with the new position.896897```ts898const $dotContainer = document.getElementById('dot-container') as HTMLDivElement899const $dot = document.getElementById('dot') as HTMLDivElement900901$dotContainer.addEventListener('pointermove', (event) => {902 positionStore.getState().setPosition({903 x: event.clientX,904 y: event.clientY,905 })906})907```908909We want to reflect the position updates on the screen by moving a div element910(representing the dot) to the new coordinates.911912```ts913const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {914 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`915}916917render(positionStore.getState(), positionStore.getState())918919positionStore.subscribe(render)920```921922Here’s the complete code.923924```ts925import { createStore } from 'zustand/vanilla'926import { persist } from 'zustand/middleware'927928type PositionStoreState = { position: { x: number; y: number } }929930type PositionStoreActions = {931 setPosition: (nextPosition: PositionStoreState['position']) => void932}933934type PositionStore = PositionStoreState & PositionStoreActions935936const positionStore = createStore<PositionStore>()(937 persist(938 (set) => ({939 position: { x: 0, y: 0 },940 setPosition: (position) => set({ position }),941 }),942 {943 name: 'position-storage',944 skipHydration: true,945 },946 ),947)948949const $dotContainer = document.getElementById('dot-container') as HTMLDivElement950const $dot = document.getElementById('dot') as HTMLDivElement951952$dotContainer.addEventListener('pointermove', (event) => {953 positionStore.getState().setPosition({954 x: event.clientX,955 y: event.clientY,956 })957})958959const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {960 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`961}962963setTimeout(() => {964 positionStore.persist.rehydrate()965}, 2000)966967render(positionStore.getState(), positionStore.getState())968969positionStore.subscribe(render)970```971972Here's the `html` code973974```html975<div976 id="dot-container"977 style="position: relative; width: 100vw; height: 100vh;"978>979 <div980 id="dot"981 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"982 ></div>983</div>984```985986## Troubleshooting987988TBD
deleted:docs/middlewares/redux.md-172 removed
1---2title: redux3description: How to use actions and reducers in a store4nav: 2085---67# redux89`redux` middleware lets you update a store through actions and reducers just like redux.1011```js12const nextStateCreatorFn = redux(reducerFn, initialState)13```1415- [Types](#types)16 - [Signature](#signature)17 - [Mutator](#mutator)18- [Reference](#reference)19- [Usage](#usage)20 - [Updating state through actions and reducers](#updating-state-through-actions-and-reducers)21- [Troubleshooting](#troubleshooting)2223## Types2425### Signature2627```ts28redux<T, A>(reducerFn: (state: T, action: A) => T, initialState: T): StateCreator<T & { dispatch: (action: A) => A }, [['zustand/redux', A]], []>29```3031### Mutator3233<!-- prettier-ignore-start -->34```ts35['zustand/redux', A]36```37<!-- prettier-ignore-end -->3839## Reference4041### `redux(reducerFn, initialState)`4243#### Parameters4445- `reducerFn`: It should be pure and should take the current state of your application and an action46 object as arguments, and returns the new state resulting from applying the action.47- `initialState`: The value you want the state to be initially. It can be a value of any type,48 except a function.4950#### Returns5152`redux` returns a state creator function.5354## Usage5556### Updating state through actions and reducers5758```ts59import { createStore } from 'zustand/vanilla'60import { redux } from 'zustand/middleware'6162type PersonStoreState = {63 firstName: string64 lastName: string65 email: string66}6768type PersonStoreAction =69 | { type: 'person/setFirstName'; firstName: string }70 | { type: 'person/setLastName'; lastName: string }71 | { type: 'person/setEmail'; email: string }7273type PersonStore = PersonStoreState & {74 dispatch: (action: PersonStoreAction) => PersonStoreAction75}7677const personStoreReducer = (78 state: PersonStoreState,79 action: PersonStoreAction,80) => {81 switch (action.type) {82 case 'person/setFirstName': {83 return { ...state, firstName: action.firstName }84 }85 case 'person/setLastName': {86 return { ...state, lastName: action.lastName }87 }88 case 'person/setEmail': {89 return { ...state, email: action.email }90 }91 default: {92 return state93 }94 }95}9697const personStoreInitialState: PersonStoreState = {98 firstName: 'Barbara',99 lastName: 'Hepworth',100 email: 'bhepworth@sculpture.com',101}102103const personStore = createStore<PersonStore>()(104 redux(personStoreReducer, personStoreInitialState),105)106107const $firstNameInput = document.getElementById(108 'first-name',109) as HTMLInputElement110const $lastNameInput = document.getElementById('last-name') as HTMLInputElement111const $emailInput = document.getElementById('email') as HTMLInputElement112const $result = document.getElementById('result') as HTMLDivElement113114function handleFirstNameChange(event: Event) {115 personStore.dispatch({116 type: 'person/setFirstName',117 firstName: (event.target as any).value,118 })119}120121function handleLastNameChange(event: Event) {122 personStore.dispatch({123 type: 'person/setLastName',124 lastName: (event.target as any).value,125 })126}127128function handleEmailChange(event: Event) {129 personStore.dispatch({130 type: 'person/setEmail',131 email: (event.target as any).value,132 })133}134135$firstNameInput.addEventListener('input', handleFirstNameChange)136$lastNameInput.addEventListener('input', handleLastNameChange)137$emailInput.addEventListener('input', handleEmailChange)138139const render: Parameters<typeof personStore.subscribe>[0] = (person) => {140 $firstNameInput.value = person.firstName141 $lastNameInput.value = person.lastName142 $emailInput.value = person.email143144 $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`145}146147render(personStore.getInitialState(), personStore.getInitialState())148149personStore.subscribe(render)150```151152Here's the `html` code153154```html155<label style="display: block">156 First name:157 <input id="first-name" />158</label>159<label style="display: block">160 Last name:161 <input id="last-name" />162</label>163<label style="display: block">164 Email:165 <input id="email" />166</label>167<p id="result"></p>168```169170## Troubleshooting171172TBD
deleted:docs/middlewares/subscribe-with-selector.md-121 removed
1---2title: subscribeWithSelector3description: How to subscribe to granular store updates in a store4nav: 2105---67# subscribeWithSelector89`subscribeWithSelector` middleware lets you subscribe to specific data based on current state.1011```js12const nextStateCreatorFn = subscribeWithSelector(stateCreatorFn)13```1415- [Types](#types)16 - [Signature](#signature)17 - [Mutator](#mutator)18- [Reference](#reference)19- [Usage](#usage)20- [Troubleshooting](#troubleshooting)2122## Types2324### Signature2526```ts27subscribeWithSelector<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/subscribeWithSelector', never]], []>28```2930### Mutator3132<!-- prettier-ignore-start -->33```ts34['zustand/subscribeWithSelector', never]35```36<!-- prettier-ignore-end -->3738## Reference3940### `subscribeWithSelector(stateCreatorFn)`4142#### Parameters4344- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.45 Usually, you will return an object with the methods you want to expose.4647#### Returns4849`subscribeWithSelector` returns a state creator function.5051## Usage5253### Subscribing partial state updates5455By subscribing to partial state updates, you register a callback that fires whenever the store's56partial state updates. We can use `subscribe` for external state management.5758```ts59import { createStore } from 'zustand/vanilla'60import { subscribeWithSelector } from 'zustand/middleware'6162type PositionStoreState = { position: { x: number; y: number } }6364type PositionStoreActions = {65 setPosition: (nextPosition: PositionStoreState['position']) => void66}6768type PositionStore = PositionStoreState & PositionStoreActions6970const positionStore = createStore<PositionStore>()(71 subscribeWithSelector((set) => ({72 position: { x: 0, y: 0 },73 setPosition: (position) => set({ position }),74 })),75)7677const $dot = document.getElementById('dot') as HTMLDivElement7879$dot.addEventListener('mouseenter', (event) => {80 const parent = event.currentTarget.parentElement81 const parentWidth = parent.clientWidth82 const parentHeight = parent.clientHeight8384 positionStore.getState().setPosition({85 x: Math.ceil(Math.random() * parentWidth),86 y: Math.ceil(Math.random() * parentHeight),87 })88})8990const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {91 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`92}9394render(positionStore.getInitialState(), positionStore.getInitialState())9596positionStore.subscribe((state) => state.position, render)9798const logger: Parameters<typeof positionStore.subscribe>[0] = (x) => {99 console.log('new x position', { x })100}101102positionStore.subscribe((state) => state.position.x, logger)103```104105Here's the `html` code106107```html108<div109 id="dot-container"110 style="position: relative; width: 100vw; height: 100vh;"111>112 <div113 id="dot"114 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"115 ></div>116</div>117```118119## Troubleshooting120121TBD
deleted:docs/migrations/migrating-to-v4.md-362 removed
1---2title: Migrating to v43nav: 224---56The only breaking changes are in types.7If you are using Zustand with TypeScript8or JSDoc type annotations,9this guide applies.10Otherwise, no migration is required.1112Also, it's recommended to first read13the new [TypeScript Guide](../guides/advanced-typescript.md),14so that the migration is easier to understand.1516In addition to this migration guide,17you can also check the18[diff](https://github.com/pmndrs/zustand/compare/v3.7.2...v4.0.0?short_path=37e5b4c#diff-c21e24854115b390eccde717da83f91feb2d5927a76c1485e5f0fdd0135c2afa)19of the test files in the Zustand repository from v3 to v4.2021## `create`2223**Applicable imports**2425```ts26import create from 'zustand'27import create from 'zustand/vanilla'28```2930**Change**3132```diff33- create:34- < State35- , StoreSetState = StoreApi<State>["set"]36- , StoreGetState = StoreApi<State>["get"]37- , Store = StoreApi<State>38- >39- (f: ...) => ...40+ create:41+ { <State>(): (f: ...) => ...42+ , <State, Mutators>(f: ...) => ...43+ }44```4546**Migration**4748If you are not passing any type parameters to `create`,49no migration is required.5051If you are using a "leaf" middleware like `combine` or `redux`,52remove all type parameters from `create`.5354Else, replace `create<T, ...>(...)` with `create<T>()(...)`.5556## `StateCreator`5758**Applicable imports**5960```ts61import type { StateCreator } from 'zustand'62import type { StateCreator } from 'zustand/vanilla'63```6465**Change**6667```diff68- type StateCreator69- < State70- , StoreSetState = StoreApi<State>["set"]71- , StoreGetState = StoreApi<State>["get"]72- , Store = StoreApi<State>73- > =74- ...75+ type StateCreator76+ < State77+ , InMutators extends [StoreMutatorIdentifier, unknown][] = []78+ , OutMutators extends [StoreMutatorIdentifier, unknown][] = []79+ , Return = State80+ > =81+ ...82```8384**Migration**8586If you are using `StateCreator`,87you are likely authoring a middleware88or using the "slices" pattern.89For that check the90[Authoring middlewares and advanced usage](../guides/advanced-typescript.md#authoring-middlewares-and-advanced-usage)91and [Common recipes](../guides/advanced-typescript.md#common-recipes)92sections of the TypeScript Guide.9394## `PartialState`9596**Applicable imports**9798```ts99import type { PartialState } from 'zustand'100import type { PartialState } from 'zustand/vanilla'101```102103**Change**104105```diff106- type PartialState107- < T extends State108- , K1 extends keyof T = keyof T109- , K2 extends keyof T = K1110- , K3 extends keyof T = K2111- , K4 extends keyof T = K3112- > =113- | (Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)114- | ((state: T) => Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)115+ type PartialState<T> =116+ | Partial<T>117+ | ((state: T) => Partial<T>)118```119120**Migration**121122Replace `PartialState<T, ...>` with `PartialState<T>`123and preferably turn on [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes)124in your `tsconfig.json`:125126```json127{128 "compilerOptions": {129 "exactOptionalPropertyTypes": true130 }131}132```133134We're no longer using the trick to disallow `{ foo: undefined }`135to be assigned to `Partial<{ foo: string }>`.136Instead, we're relying on the users to turn on `exactOptionalPropertyTypes`.137138## `useStore`139140**Applicable imports**141142```ts143import { useStore } from 'zustand'144import { useStore } from 'zustand/react'145```146147**Change**148149```diff150- useStore:151- { <State>(store: StoreApi<State>): State152- , <State, StateSlice>153- ( store: StoreApi<State>154- , selector: StateSelector<State, StateSlice>,155- , equals?: EqualityChecker<StateSlice>156- ): StateSlice157- }158+ useStore:159+ <Store, StateSlice = ExtractState<Store>>160+ ( store: Store161+ , selector?: StateSelector<State, StateSlice>,162+ , equals?: EqualityChecker<StateSlice>163+ )164+ => StateSlice165```166167**Migration**168169If you are not passing any type parameters to `useStore`,170no migration is required.171172If you are,173it's recommended to remove all the type parameters,174or pass the **store** type instead of the **state** type as the first parameter.175176## `UseBoundStore`177178**Applicable imports**179180```ts181import type { UseBoundStore } from 'zustand'182import type { UseBoundStore } from 'zustand/react'183```184185**Change**186187```diff188- type UseBoundStore<189- State,190- Store = StoreApi<State>191- > =192- & { (): T193- , <StateSlice>194- ( selector: StateSelector<State, StateSlice>195- , equals?: EqualityChecker<StateSlice>196- ): U197- }198- & Store199+ type UseBoundStore<Store> =200+ & (<StateSlice = ExtractState<S>>201+ ( selector?: (state: ExtractState<S>) => StateSlice202+ , equals?: (a: StateSlice, b: StateSlice) => boolean203+ ) => StateSlice204+ )205+ & S206```207208**Migration**209210Replace `UseBoundStore<T>` with `UseBoundStore<StoreApi<T>>`,211and `UseBoundStore<T, S>` with `UseBoundStore<S>`212213## `UseContextStore`214215**Applicable imports**216217```ts218import type { UseContextStore } from 'zustand/context'219```220221**Change**222223```diff224- type UseContextStore225```226227**Migration**228229Use `typeof MyContext.useStore` instead230231## `createContext`232233**Applicable imports**234235```ts236import createContext from 'zustand/context'237```238239**Change**240241```diff242 createContext:243- <State, Store = StoreApi<State>>() => ...244+ <Store>() => ...245```246247**Migration**248249Replace `createContext<T>()` with `createContext<StoreApi<T>>()`,250and `createContext<T, S>()` with `createContext<S>()`.251252## `combine`, `devtools`, `subscribeWithSelector`253254**Applicable imports**255256```ts257import { combine } from 'zustand/middleware'258import { devtools } from 'zustand/middleware'259import { subscribeWithSelector } from 'zustand/middleware'260```261262**Change**263264```diff265- combine:266- <T, U>(...) => ...267+ combine:268+ <T, U, Mps, Mcs>(...) => ...269270- devtools:271- <T>(...) => ...272+ devtools:273+ <T, Mps, Mcs>(...) => ...274275- subscribeWithSelector:276- <T>(...) => ...277+ subscribeWithSelector:278+ <T, Mps, Mcs>(...) => ...279```280281**Migration**282283If you are not passing any type parameters284to `combine`, `devtools`, or `subscribeWithSelector`,285no migration is required.286287If you are,288remove all the type parameters,289as they are inferred automatically.290291## `persist`292293**Applicable imports**294295```ts296import { persist } from 'zustand/middleware'297```298299**Change**300301```diff302- persist:303- <T, U = Partial<T>>(...) => ...304+ persist:305+ <T, Mps, Mcs, U = T>(...) => ...306```307308**Migration**309310If you are passing any type parameters,311remove them as they are inferred automatically.312313Next, if you are passing the `partialize` option,314there is no further steps required for migration.315316If you are **not** passing the `partialize` option,317you might see some compilation errors.318If you do not see any,319there is no further migration required.320321The type of partialized state is now `T` instead of `Partial<T>`,322which aligns with the runtime behavior of the default `partialize`,323which is an identity (`s => s`).324325If you see some compilation errors,326you have to find and fix the errors yourself,327because they might be indicative of unsound code.328Alternatively, the workaround will be passing329`s => s as Partial<typeof s>` to `partialize`.330If your partialized state is truly `Partial<T>`,331you should not encounter any bugs.332333The runtime behavior has not changed,334only the types are now correct.335336## `redux`337338**Applicable imports**339340```ts341import { redux } from 'zustand/middleware'342```343344**Change**345346```diff347- redux:348- <T, A>(...) => ...349+ redux:350+ <T, A, Mps, Mcs>(...) => ...351```352353**Migration**354355If you are not passing any type parameters to `redux`,356no migration is required.357358If you are,359remove all the type parameters,360and annotate only the second (action) parameter.361That is, replace `redux<T, A>((state, action) => ..., ...)`362with `redux((state, action: A) => ..., ...)`.
deleted:docs/migrations/migrating-to-v5.md-241 removed
1---2title: How to Migrate to v5 from v43nav: 234---56# How to Migrate to v5 from v478We highly recommend to update to the latest version of v4, before migrating to v5. It will show all deprecation warnings without breaking your app.910## Changes in v51112- Drop default exports13- Drop deprecated features14- Make React 18 the minimum required version15- Make use-sync-external-store a peer dependency (required for `createWithEqualityFn` and `useStoreWithEqualityFn` in `zustand/traditional`)16- Make TypeScript 4.5 the minimum required version17- Drop UMD/SystemJS support18- Organize entry points in the package.json19- Drop ES5 support20- Stricter types when setState's replace flag is set21- Persist middleware behavioral change22- Other small improvements (technically breaking changes)2324## Migration Guide2526### Using custom equality functions such as `shallow`2728The `create` function in v5 does not support customizing equality function.2930If you use custom equality function such as `shallow`,31the easiest migration is to use `createWithEqualityFn`.3233```js34// v435import { create } from 'zustand'36import { shallow } from 'zustand/shallow'3738const useCountStore = create((set) => ({39 count: 0,40 text: 'hello',41 // ...42}))4344const Component = () => {45 const { count, text } = useCountStore(46 (state) => ({47 count: state.count,48 text: state.text,49 }),50 shallow,51 )52 // ...53}54```5556That can be done with `createWithEqualityFn` in v5:5758```bash59npm install use-sync-external-store60```6162```js63// v564import { createWithEqualityFn as create } from 'zustand/traditional'6566// The rest is the same as v467```6869Alternatively, for the `shallow` use case, you can use `useShallow` hook:7071```js72// v573import { create } from 'zustand'74import { useShallow } from 'zustand/shallow'7576const useCountStore = create((set) => ({77 count: 0,78 text: 'hello',79 // ...80}))8182const Component = () => {83 const { count, text } = useCountStore(84 useShallow((state) => ({85 count: state.count,86 text: state.text,87 })),88 )89 // ...90}91```9293### Requiring stable selector outputs9495There is a behavioral change in v5 to match React default behavior.96If a selector returns a new reference, it may cause infinite loops.9798For example, this may cause infinite loops.99100```js101// v4102const [searchValue, setSearchValue] = useStore((state) => [103 state.searchValue,104 state.setSearchValue,105])106```107108The error message will be something like this:109110```plaintext111Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.112```113114To fix it, use the `useShallow` hook, which will return a stable reference.115116```js117// v5118import { useShallow } from 'zustand/shallow'119120const [searchValue, setSearchValue] = useStore(121 useShallow((state) => [state.searchValue, state.setSearchValue]),122)123```124125Here's another example that may cause infinite loops.126127```js128// v4129const action = useMainStore((state) => {130 return state.action ?? () => {}131})132```133134To fix it, make sure the selector function returns a stable reference.135136```js137// v5138139const FALLBACK_ACTION = () => {}140141const action = useMainStore((state) => {142 return state.action ?? FALLBACK_ACTION143})144```145146Alternatively, if you need v4 behavior, `createWithEqualityFn` will do.147148```js149// v5150import { createWithEqualityFn as create } from 'zustand/traditional'151```152153### Stricter types when setState's replace flag is set (Typescript only)154155```diff156- setState:157- (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean | undefined) => void;158+ setState:159+ (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: false) => void;160+ (state: T | ((state: T) => T), replace: true) => void;161```162163If you are not using the `replace` flag, no migration is required.164165If you are using the `replace` flag and it's set to `true`, you must provide a complete state object.166This change ensures that `store.setState({}, true)` (which results in an invalid state) is no longer considered valid.167168**Examples:**169170```ts171// Partial state update (valid)172store.setState({ key: 'value' })173174// Complete state replacement (valid)175store.setState({ key: 'value' }, true)176177// Incomplete state replacement (invalid)178store.setState({}, true) // Error179```180181#### Handling Dynamic `replace` Flag182183If the value of the `replace` flag is dynamic and determined at runtime, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:184185```ts186const replaceFlag = Math.random() > 0.5187const args = [{ bears: 5 }, replaceFlag] as Parameters<188 typeof useBearStore.setState189>190store.setState(...args)191```192193#### Persist middleware no longer stores item at store creation194195Previously, the `persist` middleware stored the initial state during store creation. This behavior has been removed in v5 (and v4.5.5).196197For example, in the following code, the initial state is stored in the storage.198199```js200// v4201import { create } from 'zustand'202import { persist } from 'zustand/middleware'203204const useCountStore = create(205 persist(206 () => ({207 count: Math.floor(Math.random() * 1000),208 }),209 {210 name: 'count',211 },212 ),213)214```215216In v5, this is no longer the case, and you need to explicitly set the state after store creation.217218```js219// v5220import { create } from 'zustand'221import { persist } from 'zustand/middleware'222223const useCountStore = create(224 persist(225 () => ({226 count: 0,227 }),228 {229 name: 'count',230 },231 ),232)233useCountStore.setState({234 count: Math.floor(Math.random() * 1000),235})236```237238## Links239240- https://github.com/pmndrs/zustand/pull/2138241- https://github.com/pmndrs/zustand/pull/2580
deleted:docs/previous-versions/zustand-v3-create-context.md-145 removed
1---2title: createContext from zustand/context3nav: 214---56A special `createContext` is provided since v3.5,7which avoids misusing the store hook.89> **Note**: This function is deprecated in v4 and will be removed in v5. See [Migration](#migration).1011```jsx12import create from 'zustand'13import createContext from 'zustand/context'1415const { Provider, useStore } = createContext()1617const createStore = () => create(...)1819const App = () => (20 <Provider createStore={createStore}>21 ...22 </Provider>23)2425const Component = () => {26 const state = useStore()27 const slice = useStore(selector)28 ...29```3031## createContext usage in real components3233```jsx34import create from "zustand";35import createContext from "zustand/context";3637// Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.3839const { Provider, useStore } = createContext();4041const createStore = () =>42 create((set) => ({43 bears: 0,44 increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),45 removeAllBears: () => set({ bears: 0 })46 }));4748const Button = () => {49 return (50 {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}51 <Provider createStore={createStore}>52 <ButtonChild />53 </Provider>54 );55};5657const ButtonChild = () => {58 const state = useStore();59 return (60 <div>61 {state.bears}62 <button63 onClick={() => {64 state.increasePopulation();65 }}66 >67 +68 </button>69 </div>70 );71};7273export default function App() {74 return (75 <div className="App">76 <Button />77 <Button />78 </div>79 );80}81```8283## createContext usage with initialization from props8485```tsx86import create from 'zustand'87import createContext from 'zustand/context'8889const { Provider, useStore } = createContext()9091export default function App({ initialBears }) {92 return (93 <Provider94 createStore={() =>95 create((set) => ({96 bears: initialBears,97 increase: () => set((state) => ({ bears: state.bears + 1 })),98 }))99 }100 >101 <Button />102 </Provider>103 )104}105```106107## Migration108109Discussion: https://github.com/pmndrs/zustand/discussions/1276110111Here's the new context usage with v4 API.112113```jsx114import { createContext, useContext, useRef } from 'react'115import { createStore, useStore } from 'zustand'116117const StoreContext = createContext(null)118119const StoreProvider = ({ children }) => {120 const storeRef = useRef()121 if (storeRef.current === null) {122 storeRef.current = createStore((set) => ({123 // ...124 }))125 }126 return (127 <StoreContext.Provider value={storeRef.current}>128 {children}129 </StoreContext.Provider>130 )131}132133const useStoreInContext = (selector) => {134 const store = useContext(StoreContext)135 if (!store) {136 throw new Error('Missing StoreProvider')137 }138 return useStore(store, selector)139}140```141142Or reach out to some third-party libraries that provide Zustand v3-like APIs:143144- <https://github.com/charkour/zustand-di>145- <https://github.com/arvinxx/zustand-utils>
added:docs/public/bear.jpgbinary

A binary file, added.

added:docs/public/favicon.icobinary

A binary file, added.

added:docs/reference/apis/create-store.md+517 added
1---2title: createStore3description: How to create vanilla stores4nav: 225---67`createStore` lets you create a vanilla store that exposes API utilities.89```js10const someStore = createStore(stateCreatorFn)11```1213- [Types](#types)14 - [Signature](#signature)15- [Reference](#reference)16- [Usage](#usage)17 - [Updating state based on previous state](#updating-state-based-on-previous-state)18 - [Updating Primitives in State](#updating-primitives-in-state)19 - [Updating Objects in State](#updating-objects-in-state)20 - [Updating Arrays in State](#updating-arrays-in-state)21 - [Subscribing to state updates](#subscribing-to-state-updates)22- [Troubleshooting](#troubleshooting)23 - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)2425## Types2627### Signature2829```ts30createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>31```3233## Reference3435### `createStore(stateCreatorFn)`3637#### Parameters3839- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.40 Usually, you will return an object with the methods you want to expose.4142#### Returns4344`createStore` returns a vanilla store that exposes API utilities, `setState`, `getState`,45`getInitialState` and `subscribe`.4647## Usage4849### Updating state based on previous state5051This example shows how you can support **updater functions** within **actions**.5253```tsx54import { createStore } from 'zustand/vanilla'5556type AgeStoreState = { age: number }5758type AgeStoreActions = {59 setAge: (60 nextAge:61 | AgeStoreState['age']62 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),63 ) => void64}6566type AgeStore = AgeStoreState & AgeStoreActions6768const ageStore = createStore<AgeStore>()((set) => ({69 age: 42,70 setAge: (nextAge) =>71 set((state) => ({72 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,73 })),74}))7576function increment() {77 ageStore.getState().setAge((currentAge) => currentAge + 1)78}7980const $yourAgeHeading = document.getElementById(81 'your-age',82) as HTMLHeadingElement83const $incrementBy3Button = document.getElementById(84 'increment-by-3',85) as HTMLButtonElement86const $incrementBy1Button = document.getElementById(87 'increment-by-1',88) as HTMLButtonElement8990$incrementBy3Button.addEventListener('click', () => {91 increment()92 increment()93 increment()94})9596$incrementBy1Button.addEventListener('click', () => {97 increment()98})99100const render: Parameters<typeof ageStore.subscribe>[0] = (state) => {101 $yourAgeHeading.innerHTML = `Your age: ${state.age}`102}103104render(ageStore.getInitialState(), ageStore.getInitialState())105106ageStore.subscribe(render)107```108109Here's the `html` code110111```html112<h1 id="your-age"></h1>113<button id="increment-by-3" type="button">+3</button>114<button id="increment-by-1" type="button">+1</button>115```116117### Updating Primitives in State118119State can hold any kind of JavaScript value. When you want to update built-in primitive values like120numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied121correctly, and avoid unexpected behaviors.122123> [!NOTE]124> By default, `set` function performs a shallow merge. If you need to completely replace125> the state with a new one, use the `replace` parameter set to `true`126127```ts128import { createStore } from 'zustand/vanilla'129130type XStore = number131132const xStore = createStore<XStore>()(() => 0)133134const $dotContainer = document.getElementById('dot-container') as HTMLDivElement135const $dot = document.getElementById('dot') as HTMLDivElement136137$dotContainer.addEventListener('pointermove', (event) => {138 xStore.setState(event.clientX, true)139})140141const render: Parameters<typeof xStore.subscribe>[0] = (x) => {142 $dot.style.transform = `translate(${x}px, 0)`143}144145render(xStore.getInitialState(), xStore.getInitialState())146147xStore.subscribe(render)148```149150Here's the `html` code151152```html153<div154 id="dot-container"155 style="position: relative; width: 100vw; height: 100vh;"156>157 <div158 id="dot"159 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"160 ></div>161</div>162```163164### Updating Objects in State165166Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store167them in state. Instead, when you want to update an object, you need to create a new one (or make a168copy of an existing one), and then set the state to use the new object.169170By default, `set` function performs a shallow merge. For most updates where you only need to modify171specific properties, the default shallow merge is preferred as it's more efficient. To completely172replace the state with a new one, use the `replace` parameter set to `true` with caution, as it173discards any existing nested data within the state.174175```ts176import { createStore } from 'zustand/vanilla'177178type PositionStoreState = { position: { x: number; y: number } }179180type PositionStoreActions = {181 setPosition: (nextPosition: PositionStoreState['position']) => void182}183184type PositionStore = PositionStoreState & PositionStoreActions185186const positionStore = createStore<PositionStore>()((set) => ({187 position: { x: 0, y: 0 },188 setPosition: (position) => set({ position }),189}))190191const $dotContainer = document.getElementById('dot-container') as HTMLDivElement192const $dot = document.getElementById('dot') as HTMLDivElement193194$dotContainer.addEventListener('pointermove', (event) => {195 positionStore.getState().setPosition({196 x: event.clientX,197 y: event.clientY,198 })199})200201const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {202 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`203}204205render(positionStore.getInitialState(), positionStore.getInitialState())206207positionStore.subscribe(render)208```209210Here's the `html` code211212```html213<div214 id="dot-container"215 style="position: relative; width: 100vw; height: 100vh;"216>217 <div218 id="dot"219 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"220 ></div>221</div>222```223224### Updating Arrays in State225226Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in227state. Just like with objects, when you want to update an array stored in state, you need to create228a new one (or make a copy of an existing one), and then set state to use the new array.229230By default, `set` function performs a shallow merge. To update array values we should assign new231values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely232replace the state with a new one, use the `replace` parameter set to `true`.233234> [!IMPORTANT]235> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,236> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid237> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,238> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.239240```ts241import { createStore } from 'zustand/vanilla'242243type PositionStore = [number, number]244245const positionStore = createStore<PositionStore>()(() => [0, 0])246247const $dotContainer = document.getElementById('dot-container') as HTMLDivElement248const $dot = document.getElementById('dot') as HTMLDivElement249250$dotContainer.addEventListener('pointermove', (event) => {251 positionStore.setState([event.clientX, event.clientY], true)252})253254const render: Parameters<typeof positionStore.subscribe>[0] = ([x, y]) => {255 $dot.style.transform = `translate(${x}px, ${y}px)`256}257258render(positionStore.getInitialState(), positionStore.getInitialState())259260positionStore.subscribe(render)261```262263Here's the `html` code264265```html266<div267 id="dot-container"268 style="position: relative; width: 100vw; height: 100vh;"269>270 <div271 id="dot"272 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"273 ></div>274</div>275```276277### Subscribing to state updates278279By subscribing to state updates, you register a callback that fires whenever the store's state280updates. We can use `subscribe` for external state management.281282```ts283import { createStore } from 'zustand/vanilla'284285type PositionStoreState = { position: { x: number; y: number } }286287type PositionStoreActions = {288 setPosition: (nextPosition: PositionStoreState['position']) => void289}290291type PositionStore = PositionStoreState & PositionStoreActions292293const positionStore = createStore<PositionStore>()((set) => ({294 position: { x: 0, y: 0 },295 setPosition: (position) => set({ position }),296}))297298const $dot = document.getElementById('dot') as HTMLDivElement299300$dot.addEventListener('mouseenter', (event) => {301 const parent = event.currentTarget.parentElement302 const parentWidth = parent.clientWidth303 const parentHeight = parent.clientHeight304305 positionStore.getState().setPosition({306 x: Math.ceil(Math.random() * parentWidth),307 y: Math.ceil(Math.random() * parentHeight),308 })309})310311const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {312 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`313}314315render(positionStore.getInitialState(), positionStore.getInitialState())316317positionStore.subscribe(render)318319const logger: Parameters<typeof positionStore.subscribe>[0] = (state) => {320 console.log('new position', { position: state.position })321}322323positionStore.subscribe(logger)324```325326Here's the `html` code327328```html329<div330 id="dot-container"331 style="position: relative; width: 100vw; height: 100vh;"332>333 <div334 id="dot"335 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"336 ></div>337</div>338```339340## Troubleshooting341342### I’ve updated the state, but the screen doesn’t update343344In the previous example, the `position` object is always created fresh from the current cursor345position. But often, you will want to include existing data as a part of the new object you’re346creating. For example, you may want to update only one field in a form, but keep the previous347values for all other fields.348349These input fields don’t work because the `oninput` handlers mutate the state:350351```ts352import { createStore } from 'zustand/vanilla'353354type PersonStoreState = {355 person: { firstName: string; lastName: string; email: string }356}357358type PersonStoreActions = {359 setPerson: (nextPerson: PersonStoreState['person']) => void360}361362type PersonStore = PersonStoreState & PersonStoreActions363364const personStore = createStore<PersonStore>()((set) => ({365 person: {366 firstName: 'Barbara',367 lastName: 'Hepworth',368 email: 'bhepworth@sculpture.com',369 },370 setPerson: (person) => set({ person }),371}))372373const $firstNameInput = document.getElementById(374 'first-name',375) as HTMLInputElement376const $lastNameInput = document.getElementById('last-name') as HTMLInputElement377const $emailInput = document.getElementById('email') as HTMLInputElement378const $result = document.getElementById('result') as HTMLDivElement379380function handleFirstNameChange(event: Event) {381 personStore.getState().person.firstName = (event.target as any).value382}383384function handleLastNameChange(event: Event) {385 personStore.getState().person.lastName = (event.target as any).value386}387388function handleEmailChange(event: Event) {389 personStore.getState().person.email = (event.target as any).value390}391392$firstNameInput.addEventListener('input', handleFirstNameChange)393$lastNameInput.addEventListener('input', handleLastNameChange)394$emailInput.addEventListener('input', handleEmailChange)395396const render: Parameters<typeof personStore.subscribe>[0] = (state) => {397 $firstNameInput.value = state.person.firstName398 $lastNameInput.value = state.person.lastName399 $emailInput.value = state.person.email400401 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`402}403404render(personStore.getInitialState(), personStore.getInitialState())405406personStore.subscribe(render)407```408409Here's the `html` code410411```html412<label style="display: block">413 First name:414 <input id="first-name" />415</label>416<label style="display: block">417 Last name:418 <input id="last-name" />419</label>420<label style="display: block">421 Email:422 <input id="email" />423</label>424<p id="result"></p>425```426427For example, this line mutates the state from a past render:428429```ts430personStore.getState().firstName = (e.target as any).value431```432433The reliable way to get the behavior you’re looking for is to create a new object and pass it to434`setPerson`. But here you want to also copy the existing data into it because only one of the435fields has changed:436437```ts438personStore.getState().setPerson({439 firstName: e.target.value, // New first name from the input440})441```442443> [!NOTE]444> We don’t need to copy every property separately due to `set` function performing shallow merge by445> default.446447Now the form works!448449Notice how you didn’t declare a separate state variable for each input field. For large forms,450keeping all data grouped in an object is very convenient—as long as you update it correctly!451452```ts {32-34,38-40,44-46}453import { createStore } from 'zustand/vanilla'454455type PersonStoreState = {456 person: { firstName: string; lastName: string; email: string }457}458459type PersonStoreActions = {460 setPerson: (nextPerson: PersonStoreState['person']) => void461}462463type PersonStore = PersonStoreState & PersonStoreActions464465const personStore = createStore<PersonStore>()((set) => ({466 person: {467 firstName: 'Barbara',468 lastName: 'Hepworth',469 email: 'bhepworth@sculpture.com',470 },471 setPerson: (person) => set({ person }),472}))473474const $firstNameInput = document.getElementById(475 'first-name',476) as HTMLInputElement477const $lastNameInput = document.getElementById('last-name') as HTMLInputElement478const $emailInput = document.getElementById('email') as HTMLInputElement479const $result = document.getElementById('result') as HTMLDivElement480481function handleFirstNameChange(event: Event) {482 personStore.getState().setPerson({483 ...personStore.getState().person,484 firstName: (event.target as any).value,485 })486}487488function handleLastNameChange(event: Event) {489 personStore.getState().setPerson({490 ...personStore.getState().person,491 lastName: (event.target as any).value,492 })493}494495function handleEmailChange(event: Event) {496 personStore.getState().setPerson({497 ...personStore.getState().person,498 email: (event.target as any).value,499 })500}501502$firstNameInput.addEventListener('input', handleFirstNameChange)503$lastNameInput.addEventListener('input', handleLastNameChange)504$emailInput.addEventListener('input', handleEmailChange)505506const render: Parameters<typeof personStore.subscribe>[0] = (state) => {507 $firstNameInput.value = state.person.firstName508 $lastNameInput.value = state.person.lastName509 $emailInput.value = state.person.email510511 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`512}513514render(personStore.getInitialState(), personStore.getInitialState())515516personStore.subscribe(render)517```
added:docs/reference/apis/create-with-equality-fn.md+607 added
1---2title: createWithEqualityFn3description: How to create efficient stores4tag: react5nav: 236---78`createWithEqualityFn` lets you create a React Hook with API utilities attached, just like `create`.9However, it offers a way to define a custom equality check. This allows for more granular control10over when components re-render, improving performance and responsiveness.1112> [!IMPORTANT]13> In order to use `createWithEqualityFn` from `zustand/traditional` you need to install14> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.1516```js17const useSomeStore = createWithEqualityFn(stateCreatorFn, equalityFn)18```1920- [Types](#types)21 - [Signature](#createwithequalityfn-signature)22- [Reference](#reference)23- [Usage](#usage)24 - [Updating state based on previous state](#updating-state-based-on-previous-state)25 - [Updating Primitives in State](#updating-primitives-in-state)26 - [Updating Objects in State](#updating-objects-in-state)27 - [Updating Arrays in State](#updating-arrays-in-state)28 - [Updating state with no store actions](#updating-state-with-no-store-actions)29 - [Subscribing to state updates](#subscribing-to-state-updates)30- [Troubleshooting](#troubleshooting)31 - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)3233## Types3435### Signature3637```ts38createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, equalityFn?: (a: T, b: T) => boolean): UseBoundStore<StoreApi<T>>39```4041## Reference4243### `createWithEqualityFn(stateCreatorFn)`4445#### Parameters4647- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.48 Usually, you will return an object with the methods you want to expose.49- **optional** `equalityFn`: Defaults to `Object.is`. A function that lets you skip re-renders.5051#### Returns5253`createWithEqualityFn` returns a React Hook with API utilities attached, just like `create`. It54lets you return data that is based on current state, using a selector function, and lets you skip55re-renders using an equality function. It should take a selector function, and an equality function56as arguments.5758## Usage5960### Updating state based on previous state6162To update a state based on previous state we should use **updater functions**. Read more63about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).6465This example shows how you can support **updater functions** within **actions**.6667```tsx68import { createWithEqualityFn } from 'zustand/traditional'69import { shallow } from 'zustand/vanilla/shallow'7071type AgeStoreState = { age: number }7273type AgeStoreActions = {74 setAge: (75 nextAge:76 | AgeStoreState['age']77 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),78 ) => void79}8081type AgeStore = AgeStoreState & AgeStoreActions8283const useAgeStore = createWithEqualityFn<AgeStore>()(84 (set) => ({85 age: 42,86 setAge: (nextAge) =>87 set((state) => ({88 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,89 })),90 }),91 shallow,92)9394export default function App() {95 const age = useAgeStore((state) => state.age)96 const setAge = useAgeStore((state) => state.setAge)9798 function increment() {99 setAge((currentAge) => currentAge + 1)100 }101102 return (103 <>104 <h1>Your age: {age}</h1>105 <button106 type="button"107 onClick={() => {108 increment()109 increment()110 increment()111 }}112 >113 +3114 </button>115 <button116 type="button"117 onClick={() => {118 increment()119 }}120 >121 +1122 </button>123 </>124 )125}126```127128### Updating Primitives in State129130State can hold any kind of JavaScript value. When you want to update built-in primitive values like131numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied132correctly, and avoid unexpected behaviors.133134> [!NOTE]135> By default, `set` function performs a shallow merge. If you need to completely replace136> the state with a new one, use the `replace` parameter set to `true`137138```tsx139import { createWithEqualityFn } from 'zustand/traditional'140import { shallow } from 'zustand/vanilla/shallow'141142type XStore = number143144const useXStore = createWithEqualityFn<XStore>()(() => 0, shallow)145146export default function MovingDot() {147 const x = useXStore()148 const setX = (nextX: number) => {149 useXStore.setState(nextX, true)150 }151 const position = { y: 0, x }152153 return (154 <div155 onPointerMove={(e) => {156 setX(e.clientX)157 }}158 style={{159 position: 'relative',160 width: '100vw',161 height: '100vh',162 }}163 >164 <div165 style={{166 position: 'absolute',167 backgroundColor: 'red',168 borderRadius: '50%',169 transform: `translate(${position.x}px, ${position.y}px)`,170 left: -10,171 top: -10,172 width: 20,173 height: 20,174 }}175 />176 </div>177 )178}179```180181### Updating Objects in State182183Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store184them in state. Instead, when you want to update an object, you need to create a new one (or make a185copy of an existing one), and then set the state to use the new object.186187By default, `set` function performs a shallow merge. For most updates where you only need to modify188specific properties, the default shallow merge is preferred as it's more efficient. To completely189replace the state with a new one, use the `replace` parameter set to `true` with caution, as it190discards any existing nested data within the state.191192```tsx193import { createWithEqualityFn } from 'zustand/traditional'194import { shallow } from 'zustand/vanilla/shallow'195196type PositionStoreState = { position: { x: number; y: number } }197198type PositionStoreActions = {199 setPosition: (nextPosition: PositionStoreState['position']) => void200}201202type PositionStore = PositionStoreState & PositionStoreActions203204const usePositionStore = createWithEqualityFn<PositionStore>()(205 (set) => ({206 position: { x: 0, y: 0 },207 setPosition: (position) => set({ position }),208 }),209 shallow,210)211212export default function MovingDot() {213 const position = usePositionStore((state) => state.position)214 const setPosition = usePositionStore((state) => state.setPosition)215216 return (217 <div218 onPointerMove={(e) => {219 setPosition({220 x: e.clientX,221 y: e.clientY,222 })223 }}224 style={{225 position: 'relative',226 width: '100vw',227 height: '100vh',228 }}229 >230 <div231 style={{232 position: 'absolute',233 backgroundColor: 'red',234 borderRadius: '50%',235 transform: `translate(${position.x}px, ${position.y}px)`,236 left: -10,237 top: -10,238 width: 20,239 height: 20,240 }}241 />242 </div>243 )244}245```246247### Updating Arrays in State248249Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in250state. Just like with objects, when you want to update an array stored in state, you need to create251a new one (or make a copy of an existing one), and then set state to use the new array.252253By default, `set` function performs a shallow merge. To update array values we should assign new254values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely255replace the state with a new one, use the `replace` parameter set to `true`.256257> [!IMPORTANT]258> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,259> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid260> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,261> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.262263```tsx264import { createWithEqualityFn } from 'zustand/traditional'265import { shallow } from 'zustand/vanilla/shallow'266267type PositionStore = [number, number]268269const usePositionStore = createWithEqualityFn<PositionStore>()(270 () => [0, 0],271 shallow,272)273274export default function MovingDot() {275 const [x, y] = usePositionStore()276 const position = { x, y }277 const setPosition: typeof usePositionStore.setState = (nextPosition) => {278 usePositionStore.setState(nextPosition, true)279 }280281 return (282 <div283 onPointerMove={(e) => {284 setPosition([e.clientX, e.clientY])285 }}286 style={{287 position: 'relative',288 width: '100vw',289 height: '100vh',290 }}291 >292 <div293 style={{294 position: 'absolute',295 backgroundColor: 'red',296 borderRadius: '50%',297 transform: `translate(${position.x}px, ${position.y}px)`,298 left: -10,299 top: -10,300 width: 20,301 height: 20,302 }}303 />304 </div>305 )306}307```308309### Updating state with no store actions310311Defining actions at module level, external to the store have a few advantages like: it doesn't312require a hook to call an action, and it facilitates code splitting.313314> [!NOTE]315> The recommended way is to colocate actions and states within the store (let your actions be316> located together with your state).317318```tsx319import { createWithEqualityFn } from 'zustand/traditional'320import { shallow } from 'zustand/vanilla/shallow'321322const usePositionStore = createWithEqualityFn<{323 x: number324 y: number325}>()(() => ({ x: 0, y: 0 }), shallow)326327const setPosition: typeof usePositionStore.setState = (nextPosition) => {328 usePositionStore.setState(nextPosition)329}330331export default function MovingDot() {332 const position = usePositionStore()333334 return (335 <div336 style={{337 position: 'relative',338 width: '100vw',339 height: '100vh',340 }}341 >342 <div343 style={{344 position: 'absolute',345 backgroundColor: 'red',346 borderRadius: '50%',347 transform: `translate(${position.x}px, ${position.y}px)`,348 left: -10,349 top: -10,350 width: 20,351 height: 20,352 }}353 onMouseEnter={(event) => {354 const parent = event.currentTarget.parentElement355 const parentWidth = parent.clientWidth356 const parentHeight = parent.clientHeight357358 setPosition({359 x: Math.ceil(Math.random() * parentWidth),360 y: Math.ceil(Math.random() * parentHeight),361 })362 }}363 />364 </div>365 )366}367```368369### Subscribing to state updates370371By subscribing to state updates, you register a callback that fires whenever the store's state372updates. We can use `subscribe` for external state management.373374```tsx375import { useEffect } from 'react'376import { createWithEqualityFn } from 'zustand/traditional'377import { shallow } from 'zustand/vanilla/shallow'378379type PositionStoreState = { position: { x: number; y: number } }380381type PositionStoreActions = {382 setPosition: (nextPosition: PositionStoreState['position']) => void383}384385type PositionStore = PositionStoreState & PositionStoreActions386387const usePositionStore = createWithEqualityFn<PositionStore>()(388 (set) => ({389 position: { x: 0, y: 0 },390 setPosition: (nextPosition) => set({ position: nextPosition }),391 }),392 shallow,393)394395export default function MovingDot() {396 const position = usePositionStore((state) => state.position)397 const setPosition = usePositionStore((state) => state.setPosition)398399 useEffect(() => {400 const unsubscribePositionStore = usePositionStore.subscribe(401 ({ position }) => {402 console.log('new position', { position })403 },404 )405406 return () => {407 unsubscribePositionStore()408 }409 }, [])410411 return (412 <div413 style={{414 position: 'relative',415 width: '100vw',416 height: '100vh',417 }}418 >419 <div420 style={{421 position: 'absolute',422 backgroundColor: 'red',423 borderRadius: '50%',424 transform: `translate(${position.x}px, ${position.y}px)`,425 left: -10,426 top: -10,427 width: 20,428 height: 20,429 }}430 onMouseEnter={(event) => {431 const parent = event.currentTarget.parentElement432 const parentWidth = parent.clientWidth433 const parentHeight = parent.clientHeight434435 setPosition({436 x: Math.ceil(Math.random() * parentWidth),437 y: Math.ceil(Math.random() * parentHeight),438 })439 }}440 />441 </div>442 )443}444```445446## Troubleshooting447448### I’ve updated the state, but the screen doesn’t update449450In the previous example, the `position` object is always created fresh from the current cursor451position. But often, you will want to include existing data as a part of the new object you’re452creating. For example, you may want to update only one field in a form, but keep the previous453values for all other fields.454455These input fields don’t work because the `onChange` handlers mutate the state:456457```tsx458import { createWithEqualityFn } from 'zustand/traditional'459import { shallow } from 'zustand/vanilla/shallow'460461type PersonStoreState = {462 person: { firstName: string; lastName: string; email: string }463}464465type PersonStoreActions = {466 setPerson: (nextPerson: PersonStoreState['person']) => void467}468469type PersonStore = PersonStoreState & PersonStoreActions470471const usePersonStore = createWithEqualityFn<PersonStore>()(472 (set) => ({473 person: {474 firstName: 'Barbara',475 lastName: 'Hepworth',476 email: 'bhepworth@sculpture.com',477 },478 setPerson: (person) => set({ person }),479 }),480 shallow,481)482483export default function Form() {484 const person = usePersonStore((state) => state.person)485 const setPerson = usePersonStore((state) => state.setPerson)486487 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {488 person.firstName = e.target.value489 }490491 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {492 person.lastName = e.target.value493 }494495 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {496 person.email = e.target.value497 }498499 return (500 <>501 <label style={{ display: 'block' }}>502 First name:503 <input value={person.firstName} onChange={handleFirstNameChange} />504 </label>505 <label style={{ display: 'block' }}>506 Last name:507 <input value={person.lastName} onChange={handleLastNameChange} />508 </label>509 <label style={{ display: 'block' }}>510 Email:511 <input value={person.email} onChange={handleEmailChange} />512 </label>513 <p>514 {person.firstName} {person.lastName} ({person.email})515 </p>516 </>517 )518}519```520521For example, this line mutates the state from a past render:522523```tsx524person.firstName = e.target.value525```526527The reliable way to get the behavior you’re looking for is to create a new object and pass it to528`setPerson`. But here you want to also copy the existing data into it because only one of the529fields has changed:530531```ts532setPerson({ ...person, firstName: e.target.value }) // New first name from the input533```534535> [!NOTE]536> We don’t need to copy every property separately due to `set` function performing shallow merge by537> default.538539Now the form works!540541Notice how you didn’t declare a separate state variable for each input field. For large forms,542keeping all data grouped in an object is very convenient—as long as you update it correctly!543544```tsx {32,36,40}545import { type ChangeEvent } from 'react'546import { createWithEqualityFn } from 'zustand/traditional'547import { shallow } from 'zustand/vanilla/shallow'548549type PersonStoreState = {550 person: { firstName: string; lastName: string; email: string }551}552553type PersonStoreActions = {554 setPerson: (nextPerson: PersonStoreState['person']) => void555}556557type PersonStore = PersonStoreState & PersonStoreActions558559const usePersonStore = createWithEqualityFn<PersonStore>()(560 (set) => ({561 person: {562 firstName: 'Barbara',563 lastName: 'Hepworth',564 email: 'bhepworth@sculpture.com',565 },566 setPerson: (nextPerson) => set({ person: nextPerson }),567 }),568 shallow,569)570571export default function Form() {572 const person = usePersonStore((state) => state.person)573 const setPerson = usePersonStore((state) => state.setPerson)574575 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {576 setPerson({ ...person, firstName: e.target.value })577 }578579 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {580 setPerson({ ...person, lastName: e.target.value })581 }582583 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {584 setPerson({ ...person, email: e.target.value })585 }586587 return (588 <>589 <label style={{ display: 'block' }}>590 First name:591 <input value={person.firstName} onChange={handleFirstNameChange} />592 </label>593 <label style={{ display: 'block' }}>594 Last name:595 <input value={person.lastName} onChange={handleLastNameChange} />596 </label>597 <label style={{ display: 'block' }}>598 Email:599 <input value={person.email} onChange={handleEmailChange} />600 </label>601 <p>602 {person.firstName} {person.lastName} ({person.email})603 </p>604 </>605 )606}607```
added:docs/reference/apis/create.md+571 added
1---2title: create3description: How to create stores4tag: react5nav: 216---78`create` lets you create a React Hook with API utilities attached.910```js11const useSomeStore = create(stateCreatorFn)12```1314- [Types](#types)15 - [Signature](#create-signature)16- [Reference](#reference)17- [Usage](#usage)18 - [Updating state based on previous state](#updating-state-based-on-previous-state)19 - [Updating Primitives in State](#updating-primitives-in-state)20 - [Updating Objects in State](#updating-objects-in-state)21 - [Updating Arrays in State](#updating-arrays-in-state)22 - [Updating state with no store actions](#updating-state-with-no-store-actions)23 - [Subscribing to state updates](#subscribing-to-state-updates)24- [Troubleshooting](#troubleshooting)25 - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)2627## Types2829### Signature3031```ts32create<T>()(stateCreatorFn: StateCreator<T, [], []>): UseBoundStore<StoreApi<T>>33```3435## Reference3637### `create(stateCreatorFn)`3839#### Parameters4041- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.42 Usually, you will return an object with the methods you want to expose.4344#### Returns4546`create` returns a React Hook with API utilities, `setState`, `getState`, `getInitialState` and47`subscribe`, attached. It lets you return data that is based on current state, using a selector48function. It should take a selector function as its only argument.4950## Usage5152### Updating state based on previous state5354To update a state based on previous state we should use **updater functions**. Read more55about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).5657This example shows how you can support **updater functions** within **actions**.5859```tsx60import { create } from 'zustand'6162type AgeStoreState = { age: number }6364type AgeStoreActions = {65 setAge: (66 nextAge:67 | AgeStoreState['age']68 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),69 ) => void70}7172type AgeStore = AgeStoreState & AgeStoreActions7374const useAgeStore = create<AgeStore>()((set) => ({75 age: 42,76 setAge: (nextAge) => {77 set((state) => ({78 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,79 }))80 },81}))8283export default function App() {84 const age = useAgeStore((state) => state.age)85 const setAge = useAgeStore((state) => state.setAge)8687 function increment() {88 setAge((currentAge) => currentAge + 1)89 }9091 return (92 <>93 <h1>Your age: {age}</h1>94 <button95 onClick={() => {96 increment()97 increment()98 increment()99 }}100 >101 +3102 </button>103 <button104 onClick={() => {105 increment()106 }}107 >108 +1109 </button>110 </>111 )112}113```114115### Updating Primitives in State116117State can hold any kind of JavaScript value. When you want to update built-in primitive values like118numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied119correctly, and avoid unexpected behaviors.120121> [!NOTE]122> By default, `set` function performs a shallow merge. If you need to completely replace the state123> with a new one, use the `replace` parameter set to `true`124125```tsx126import { create } from 'zustand'127128type XStore = number129130const useXStore = create<XStore>()(() => 0)131132export default function MovingDot() {133 const x = useXStore()134 const setX = (nextX: number) => {135 useXStore.setState(nextX, true)136 }137 const position = { y: 0, x }138139 return (140 <div141 onPointerMove={(e) => {142 setX(e.clientX)143 }}144 style={{145 position: 'relative',146 width: '100vw',147 height: '100vh',148 }}149 >150 <div151 style={{152 position: 'absolute',153 backgroundColor: 'red',154 borderRadius: '50%',155 transform: `translate(${position.x}px, ${position.y}px)`,156 left: -10,157 top: -10,158 width: 20,159 height: 20,160 }}161 />162 </div>163 )164}165```166167### Updating Objects in State168169Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store170them in state. Instead, when you want to update an object, you need to create a new one (or make a171copy of an existing one), and then set the state to use the new object.172173By default, `set` function performs a shallow merge. For most updates where you only need to modify174specific properties, the default shallow merge is preferred as it's more efficient. To completely175replace the state with a new one, use the `replace` parameter set to `true` with caution, as it176discards any existing nested data within the state.177178```tsx179import { create } from 'zustand'180181type PositionStoreState = { position: { x: number; y: number } }182183type PositionStoreActions = {184 setPosition: (nextPosition: PositionStoreState['position']) => void185}186187type PositionStore = PositionStoreState & PositionStoreActions188189const usePositionStore = create<PositionStore>()((set) => ({190 position: { x: 0, y: 0 },191 setPosition: (nextPosition) => set({ position: nextPosition }),192}))193194export default function MovingDot() {195 const position = usePositionStore((state) => state.position)196 const setPosition = usePositionStore((state) => state.setPosition)197198 return (199 <div200 onPointerMove={(e) => {201 setPosition({202 x: e.clientX,203 y: e.clientY,204 })205 }}206 style={{207 position: 'relative',208 width: '100vw',209 height: '100vh',210 }}211 >212 <div213 style={{214 position: 'absolute',215 backgroundColor: 'red',216 borderRadius: '50%',217 transform: `translate(${position.x}px, ${position.y}px)`,218 left: -10,219 top: -10,220 width: 20,221 height: 20,222 }}223 />224 </div>225 )226}227```228229### Updating Arrays in State230231Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in232state. Just like with objects, when you want to update an array stored in state, you need to create233a new one (or make a copy of an existing one), and then set state to use the new array.234235By default, `set` function performs a shallow merge. To update array values we should assign new236values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely237replace the state with a new one, use the `replace` parameter set to `true`.238239> [!IMPORTANT]240> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,241> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid242> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,243> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.244245```tsx246import { create } from 'zustand'247248type PositionStore = [number, number]249250const usePositionStore = create<PositionStore>()(() => [0, 0])251252export default function MovingDot() {253 const [x, y] = usePositionStore()254 const setPosition: typeof usePositionStore.setState = (nextPosition) => {255 usePositionStore.setState(nextPosition, true)256 }257 const position = { x, y }258259 return (260 <div261 onPointerMove={(e) => {262 setPosition([e.clientX, e.clientY])263 }}264 style={{265 position: 'relative',266 width: '100vw',267 height: '100vh',268 }}269 >270 <div271 style={{272 position: 'absolute',273 backgroundColor: 'red',274 borderRadius: '50%',275 transform: `translate(${position.x}px, ${position.y}px)`,276 left: -10,277 top: -10,278 width: 20,279 height: 20,280 }}281 />282 </div>283 )284}285```286287### Updating state with no store actions288289Defining actions at module level, external to the store have a few advantages like: it doesn't290require a hook to call an action, and it facilitates code splitting.291292> [!NOTE]293> The recommended way is to colocate actions and states within the store (let your actions be294> located together with your state).295296```tsx297import { create } from 'zustand'298299const usePositionStore = create<{300 x: number301 y: number302}>()(() => ({ x: 0, y: 0 }))303304const setPosition: typeof usePositionStore.setState = (nextPosition) => {305 usePositionStore.setState(nextPosition)306}307308export default function MovingDot() {309 const position = usePositionStore()310311 return (312 <div313 style={{314 position: 'relative',315 width: '100vw',316 height: '100vh',317 }}318 >319 <div320 style={{321 position: 'absolute',322 backgroundColor: 'red',323 borderRadius: '50%',324 transform: `translate(${position.x}px, ${position.y}px)`,325 left: -10,326 top: -10,327 width: 20,328 height: 20,329 }}330 onMouseEnter={(event) => {331 const parent = event.currentTarget.parentElement332 const parentWidth = parent.clientWidth333 const parentHeight = parent.clientHeight334335 setPosition({336 x: Math.ceil(Math.random() * parentWidth),337 y: Math.ceil(Math.random() * parentHeight),338 })339 }}340 />341 </div>342 )343}344```345346### Subscribing to state updates347348By subscribing to state updates, you register a callback that fires whenever the store's state349updates. We can use `subscribe` for external state management.350351```tsx352import { useEffect } from 'react'353import { create } from 'zustand'354355type PositionStoreState = { position: { x: number; y: number } }356357type PositionStoreActions = {358 setPosition: (nextPosition: PositionStoreState['position']) => void359}360361type PositionStore = PositionStoreState & PositionStoreActions362363const usePositionStore = create<PositionStore>()((set) => ({364 position: { x: 0, y: 0 },365 setPosition: (nextPosition) => set({ position: nextPosition }),366}))367368export default function MovingDot() {369 const position = usePositionStore((state) => state.position)370 const setPosition = usePositionStore((state) => state.setPosition)371372 useEffect(() => {373 const unsubscribePositionStore = usePositionStore.subscribe(374 ({ position }) => {375 console.log('new position', { position })376 },377 )378379 return () => {380 unsubscribePositionStore()381 }382 }, [])383384 return (385 <div386 style={{387 position: 'relative',388 width: '100vw',389 height: '100vh',390 }}391 >392 <div393 style={{394 position: 'absolute',395 backgroundColor: 'red',396 borderRadius: '50%',397 transform: `translate(${position.x}px, ${position.y}px)`,398 left: -10,399 top: -10,400 width: 20,401 height: 20,402 }}403 onMouseEnter={(event) => {404 const parent = event.currentTarget.parentElement405 const parentWidth = parent.clientWidth406 const parentHeight = parent.clientHeight407408 setPosition({409 x: Math.ceil(Math.random() * parentWidth),410 y: Math.ceil(Math.random() * parentHeight),411 })412 }}413 />414 </div>415 )416}417```418419## Troubleshooting420421### I’ve updated the state, but the screen doesn’t update422423In the previous example, the `position` object is always created fresh from the current cursor424position. But often, you will want to include existing data as a part of the new object you’re425creating. For example, you may want to update only one field in a form, but keep the previous426values for all other fields.427428These input fields don’t work because the `onChange` handlers mutate the state:429430```tsx431import { create } from 'zustand'432433type PersonStoreState = {434 firstName: string435 lastName: string436 email: string437}438439type PersonStoreActions = {440 setPerson: (nextPerson: Partial<PersonStoreState>) => void441}442443type PersonStore = PersonStoreState & PersonStoreActions444445const usePersonStore = create<PersonStore>()((set) => ({446 firstName: 'Barbara',447 lastName: 'Hepworth',448 email: 'bhepworth@sculpture.com',449 setPerson: (nextPerson) => set(nextPerson),450}))451452export default function Form() {453 const person = usePersonStore((state) => state)454 const setPerson = usePersonStore((state) => state.setPerson)455456 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {457 person.firstName = e.target.value458 }459460 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {461 person.lastName = e.target.value462 }463464 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {465 person.email = e.target.value466 }467468 return (469 <>470 <label style={{ display: 'block' }}>471 First name:472 <input value={person.firstName} onChange={handleFirstNameChange} />473 </label>474 <label style={{ display: 'block' }}>475 Last name:476 <input value={person.lastName} onChange={handleLastNameChange} />477 </label>478 <label style={{ display: 'block' }}>479 Email:480 <input value={person.email} onChange={handleEmailChange} />481 </label>482 <p>483 {person.firstName} {person.lastName} ({person.email})484 </p>485 </>486 )487}488```489490For example, this line mutates the state from a past render:491492```tsx493person.firstName = e.target.value494```495496The reliable way to get the behavior you’re looking for is to create a new object and pass it to497`setPerson`. But here you want to also copy the existing data into it because only one of the498fields has changed:499500```ts501setPerson({ ...person, firstName: e.target.value }) // New first name from the input502```503504> [!NOTE]505> We don’t need to copy every property separately due to `set` function performing shallow merge by506> default.507508Now the form works!509510Notice how you didn’t declare a separate state variable for each input field. For large forms,511keeping all data grouped in an object is very convenient—as long as you update it correctly!512513```tsx {27,31,35}514import { create } from 'zustand'515516type PersonStoreState = {517 person: { firstName: string; lastName: string; email: string }518}519520type PersonStoreActions = {521 setPerson: (nextPerson: PersonStoreState['person']) => void522}523524type PersonStore = PersonStoreState & PersonStoreActions525526const usePersonStore = create<PersonStore>()((set) => ({527 person: {528 firstName: 'Barbara',529 lastName: 'Hepworth',530 email: 'bhepworth@sculpture.com',531 },532 setPerson: (nextPerson) => set(nextPerson),533}))534535export default function Form() {536 const person = usePersonStore((state) => state.person)537 const setPerson = usePersonStore((state) => state.setPerson)538539 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {540 setPerson({ ...person, firstName: e.target.value })541 }542543 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {544 setPerson({ ...person, lastName: e.target.value })545 }546547 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {548 setPerson({ ...person, email: e.target.value })549 }550551 return (552 <>553 <label style={{ display: 'block' }}>554 First name:555 <input value={person.firstName} onChange={handleFirstNameChange} />556 </label>557 <label style={{ display: 'block' }}>558 Last name:559 <input value={person.lastName} onChange={handleLastNameChange} />560 </label>561 <label style={{ display: 'block' }}>562 Email:563 <input value={person.email} onChange={handleEmailChange} />564 </label>565 <p>566 {person.firstName} {person.lastName} ({person.email})567 </p>568 </>569 )570}571```
added:docs/reference/apis/shallow.md+248 added
1---2title: shallow3description: How compare simple data effectively4nav: 245---67`shallow` lets you run fast checks on simple data structures. It effectively identifies changes in8**top-level** properties when you're working with data structures that don't have nested objects or9arrays within them.1011> [!NOTE]12> Shallow lets you perform quick comparisons, but keep its limitations in mind.1314```js15const equal = shallow(a, b)16```1718- [Types](#types)19 - [Signature](#shallow-signature)20- [Reference](#reference)21- [Usage](#usage)22 - [Comparing Primitives](#comparing-primitives)23 - [Comparing Objects](#comparing-objects)24 - [Comparing Sets](#comparing-sets)25 - [Comparing Maps](#comparing-maps)26- [Troubleshooting](#troubleshooting)27 - [Comparing objects returns `false` even if they are identical.](#comparing-objects-returns-false-even-if-they-are-identical)28 - [Comparing objects with different prototypes](#comparing-objects-with-different-prototypes)2930## Types3132### Signature3334```ts35shallow<T>(a: T, b: T): boolean36```3738## Reference3940### `shallow(a, b)`4142#### Parameters4344- `a`: The first value.45- `b`: The second value.4647#### Returns4849`shallow` returns `true` when `a` and `b` are equal based on a shallow comparison of their50**top-level** properties. Otherwise, it should return `false`.5152## Usage5354### Comparing Primitives5556When comparing primitive values like `string`s, `number`s, `boolean`s, and `BigInt`s, both57`Object.is` and `shallow` function return `true` if the values are the same. This is because58primitive values are compared by their actual value rather than by reference.5960```ts61const stringLeft = 'John Doe'62const stringRight = 'John Doe'6364Object.is(stringLeft, stringRight) // -> true65shallow(stringLeft, stringRight) // -> true6667const numberLeft = 1068const numberRight = 106970Object.is(numberLeft, numberRight) // -> true71shallow(numberLeft, numberRight) // -> true7273const booleanLeft = true74const booleanRight = true7576Object.is(booleanLeft, booleanRight) // -> true77shallow(booleanLeft, booleanRight) // -> true7879const bigIntLeft = 1n80const bigIntRight = 1n8182Object.is(bigIntLeft, bigIntRight) // -> true83shallow(bigIntLeft, bigIntRight) // -> true84```8586### Comparing Objects8788When comparing objects, it's important to understand how `Object.is` and `shallow` function89operate, as they handle comparisons differently.9091The `shallow` function returns `true` because shallow performs a shallow comparison of the objects.92It checks if the top-level properties and their values are the same. In this case, the top-level93properties (`firstName`, `lastName`, and `age`) and their values are identical between `objectLeft`94and `objectRight`, so shallow considers them equal.9596```ts97const objectLeft = {98 firstName: 'John',99 lastName: 'Doe',100 age: 30,101}102const objectRight = {103 firstName: 'John',104 lastName: 'Doe',105 age: 30,106}107108Object.is(objectLeft, objectRight) // -> false109shallow(objectLeft, objectRight) // -> true110```111112### Comparing Sets113114When comparing sets, it's important to understand how `Object.is` and `shallow` function operate,115as they handle comparisons differently.116117The `shallow` function returns `true` because shallow performs a shallow comparison of the sets. It118checks if the top-level properties (in this case, the sets themselves) are the same. Since `setLeft`119and `setRight` are both instances of the Set object and contain the same elements, shallow considers120them equal.121122```ts123const setLeft = new Set([1, 2, 3])124const setRight = new Set([1, 2, 3])125126Object.is(setLeft, setRight) // -> false127shallow(setLeft, setRight) // -> true128```129130### Comparing Maps131132When comparing maps, it's important to understand how `Object.is` and `shallow` function operate, as133they handle comparisons differently.134135The `shallow` returns `true` because shallow performs a shallow comparison of the maps. It checks if136the top-level properties (in this case, the maps themselves) are the same. Since `mapLeft` and137`mapRight` are both instances of the Map object and contain the same key-value pairs, shallow138considers them equal.139140```ts141const mapLeft = new Map([142 [1, 'one'],143 [2, 'two'],144 [3, 'three'],145])146const mapRight = new Map([147 [1, 'one'],148 [2, 'two'],149 [3, 'three'],150])151152Object.is(mapLeft, mapRight) // -> false153shallow(mapLeft, mapRight) // -> true154```155156## Troubleshooting157158### Comparing objects returns `false` even if they are identical.159160The `shallow` function performs a shallow comparison. A shallow comparison checks if the top-level161properties of two objects are equal. It does not check nested objects or deeply nested properties.162In other words, it only compares the references of the properties.163164In the following example, the shallow function returns `false` because it compares only the165top-level properties and their references. The address property in both objects is a nested object,166and even though their contents are identical, their references are different. Consequently, shallow167sees them as different, resulting in `false`.168169```ts170const objectLeft = {171 firstName: 'John',172 lastName: 'Doe',173 age: 30,174 address: {175 street: 'Kulas Light',176 suite: 'Apt. 556',177 city: 'Gwenborough',178 zipcode: '92998-3874',179 geo: {180 lat: '-37.3159',181 lng: '81.1496',182 },183 },184}185const objectRight = {186 firstName: 'John',187 lastName: 'Doe',188 age: 30,189 address: {190 street: 'Kulas Light',191 suite: 'Apt. 556',192 city: 'Gwenborough',193 zipcode: '92998-3874',194 geo: {195 lat: '-37.3159',196 lng: '81.1496',197 },198 },199}200201Object.is(objectLeft, objectRight) // -> false202shallow(objectLeft, objectRight) // -> false203```204205If we remove the `address` property, the shallow comparison would work as expected because all206top-level properties would be primitive values or references to the same values:207208```ts209const objectLeft = {210 firstName: 'John',211 lastName: 'Doe',212 age: 30,213}214const objectRight = {215 firstName: 'John',216 lastName: 'Doe',217 age: 30,218}219220Object.is(objectLeft, objectRight) // -> false221shallow(objectLeft, objectRight) // -> true222```223224In this modified example, `objectLeft` and `objectRight` have the same top-level properties and225primitive values. Since `shallow` function only compares the top-level properties, it will return226`true` because the primitive values (`firstName`, `lastName`, and `age`) are identical in both227objects.228229### Comparing objects with different prototypes230231The `shallow` function checks whether the two objects have the same prototype. If their prototypes232are referentially different, shallow will return `false`. This comparison is done using:233234```ts235Object.getPrototypeOf(a) === Object.getPrototypeOf(b)236```237238> [!IMPORTANT]239> Objects created with the object initializer (`{}`) or with `new Object()` inherit from240> `Object.prototype` by default. However, objects created with `Object.create(proto)` inherit from241> the proto you pass in—which may not be `Object.prototype.`242243```ts244const a = Object.create({}) // -> prototype is `{}`245const b = {} // -> prototype is `Object.prototype`246247shallow(a, b) // -> false248```
added:docs/reference/hooks/use-shallow.md+267 added
1---2title: useShallow3description: How to memoize selector functions4tag: react5nav: 276---78`useShallow` is a React Hook that lets you optimize re-renders.910```js11const memoizedSelector = useShallow(selector)12```1314- [Types](#types)15 - [Signature](#signature)16- [Reference](#reference)17- [Usage](#usage)18 - [Writing a memoized selector](#writing-a-memoized-selector)19- [Troubleshooting](#troubleshooting)2021### Signature2223```ts24useShallow<T, U = T>(selectorFn: (state: T) => U): (state: T) => U25```2627## Reference2829### `useShallow(selectorFn)`3031#### Parameters3233- `selectorFn`: A function that lets you return data that is based on current state.3435#### Returns3637`useShallow` returns a memoized version of a selector function using a shallow comparison for38memoization.3940## Usage4142### Writing a memoized selector4344First, we need to setup a store to hold the state for the bear family. In this store, we define45three properties: `papaBear`, `mamaBear`, and `babyBear`, each representing a different member of46the bear family and their respective oatmeal pot sizes.4748```tsx49import { create } from 'zustand'5051type BearFamilyMealsStore = {52 [key: string]: string53}5455const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({56 papaBear: 'large porridge-pot',57 mamaBear: 'middle-size porridge pot',58 babyBear: 'A little, small, wee pot',59}))60```6162Next, we'll create a `BearNames` component that retrieves the keys of our state (the bear family63members) and displays them.6465```tsx66function BearNames() {67 const names = useBearFamilyMealsStore((state) => Object.keys(state))6869 return <div>{names.join(', ')}</div>70}71```7273Next, we will create a `UpdateBabyBearMeal` component that periodically updates baby bear's meal74choice.7576```tsx77const meals = [78 'A tiny, little, wee bowl',79 'A small, petite, tiny pot',80 'A wee, itty-bitty, small bowl',81 'A little, petite, tiny dish',82 'A tiny, small, wee vessel',83 'A small, little, wee cauldron',84 'A little, tiny, small cup',85 'A wee, small, little jar',86 'A tiny, wee, small pan',87 'A small, wee, little crock',88]8990function UpdateBabyBearMeal() {91 useEffect(() => {92 const timer = setInterval(() => {93 useBearFamilyMealsStore.setState({94 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],95 })96 }, 1000)9798 return () => {99 clearInterval(timer)100 }101 }, [])102103 return null104}105```106107Finally, we combine both components in the `App` component to see them in action.108109```tsx110export default function App() {111 return (112 <>113 <UpdateBabyBearMeal />114 <BearNames />115 </>116 )117}118```119120Here is what the code should look like:121122```tsx123import { useEffect } from 'react'124import { create } from 'zustand'125126type BearFamilyMealsStore = {127 [key: string]: string128}129130const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({131 papaBear: 'large porridge-pot',132 mamaBear: 'middle-size porridge pot',133 babyBear: 'A little, small, wee pot',134}))135136const meals = [137 'A tiny, little, wee bowl',138 'A small, petite, tiny pot',139 'A wee, itty-bitty, small bowl',140 'A little, petite, tiny dish',141 'A tiny, small, wee vessel',142 'A small, little, wee cauldron',143 'A little, tiny, small cup',144 'A wee, small, little jar',145 'A tiny, wee, small pan',146 'A small, wee, little crock',147]148149function UpdateBabyBearMeal() {150 useEffect(() => {151 const timer = setInterval(() => {152 useBearFamilyMealsStore.setState({153 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],154 })155 }, 1000)156157 return () => {158 clearInterval(timer)159 }160 }, [])161162 return null163}164165function BearNames() {166 const names = useBearFamilyMealsStore((state) => Object.keys(state))167168 return <div>{names.join(', ')}</div>169}170171export default function App() {172 return (173 <>174 <UpdateBabyBearMeal />175 <BearNames />176 </>177 )178}179```180181Everything might look fine, but there’s a small problem: the `BearNames` component keeps182re-rendering even if the names haven’t changed. This happens because the component re-renders183whenever any part of the state changes, even if the specific part we care about (the list of names) hasn’t changed.184185To fix this, we use `useShallow` to make sure the component only re-renders when the actual keys of186the state change:187188```tsx189function BearNames() {190 const names = useBearFamilyMealsStore(191 useShallow((state) => Object.keys(state)),192 )193194 return <div>{names.join(', ')}</div>195}196```197198Here is what the code should look like:199200```tsx201import { useEffect } from 'react'202import { create } from 'zustand'203import { useShallow } from 'zustand/react/shallow'204205type BearFamilyMealsStore = {206 [key: string]: string207}208209const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({210 papaBear: 'large porridge-pot',211 mamaBear: 'middle-size porridge pot',212 babyBear: 'A little, small, wee pot',213}))214215const meals = [216 'A tiny, little, wee bowl',217 'A small, petite, tiny pot',218 'A wee, itty-bitty, small bowl',219 'A little, petite, tiny dish',220 'A tiny, small, wee vessel',221 'A small, little, wee cauldron',222 'A little, tiny, small cup',223 'A wee, small, little jar',224 'A tiny, wee, small pan',225 'A small, wee, little crock',226]227228function UpdateBabyBearMeal() {229 useEffect(() => {230 const timer = setInterval(() => {231 useBearFamilyMealsStore.setState({232 babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],233 })234 }, 1000)235236 return () => {237 clearInterval(timer)238 }239 }, [])240241 return null242}243244function BearNames() {245 const names = useBearFamilyMealsStore(246 useShallow((state) => Object.keys(state)),247 )248249 return <div>{names.join(', ')}</div>250}251252export default function App() {253 return (254 <>255 <UpdateBabyBearMeal />256 <BearNames />257 </>258 )259}260```261262By using `useShallow`, we optimized the rendering process, ensuring that the component only263re-renders when necessary, which improves overall performance.264265## Troubleshooting266267TBD
added:docs/reference/hooks/use-store-with-equality-fn.md+957 added
1---2title: useStoreWithEqualityFn3description: How to use vanilla stores effectively in React4tag: react5nav: 266---78`useStoreWithEqualityFn` is a React Hook that lets you use a vanilla store in React, just like9`useStore`. However, it offers a way to define a custom equality check. This allows for more10granular control over when components re-render, improving performance and responsiveness.1112> [!IMPORTANT]13> In order to use `useStoreWithEqualityFn` from `zustand/traditional` you need to install14> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.1516```js17const someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)18```1920- [Types](#types)21 - [Signature](#signature)22- [Reference](#reference)23- [Usage](#usage)24 - [Using a global vanilla store in React](#using-a-global-vanilla-store-in-react)25 - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)26 - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)27 - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)28- [Troubleshooting](#troubleshooting)2930### Signature3132```ts33useStoreWithEqualityFn<T, U = T>(store: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U34```3536## Reference3738### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`3940#### Parameters4142- `storeApi`: The instance that lets you access to store API utilities.43- `selectorFn`: A function that lets you return data that is based on current state.44- `equalityFn`: A function that lets you skip re-renders.4546#### Returns4748`useStoreWithEqualityFn` returns any data based on current state depending on the selector function,49and lets you skip re-renders using an equality function. It should take a store, a selector50function, and an equality function as arguments.5152## Usage5354### Using a global vanilla store in React5556First, let's set up a store that will hold the position of the dot on the screen. We'll define the57store to manage `x` and `y` coordinates and provide an action to update these coordinates.5859```tsx60import { createStore, useStore } from 'zustand'6162type PositionStoreState = { position: { x: number; y: number } }6364type PositionStoreActions = {65 setPosition: (nextPosition: PositionStoreState['position']) => void66}6768type PositionStore = PositionStoreState & PositionStoreActions6970const positionStore = createStore<PositionStore>()((set) => ({71 position: { x: 0, y: 0 },72 setPosition: (position) => set({ position }),73}))74```7576Next, we'll create a `MovingDot` component that renders a div representing the dot. This component77will use the store to track and update the dot's position.7879```tsx80function MovingDot() {81 const position = useStoreWithEqualityFn(82 positionStore,83 (state) => state.position,84 shallow,85 )86 const setPosition = useStoreWithEqualityFn(87 positionStore,88 (state) => state.setPosition,89 shallow,90 )9192 return (93 <div94 onPointerMove={(e) => {95 setPosition({96 x: e.clientX,97 y: e.clientY,98 })99 }}100 style={{101 position: 'relative',102 width: '100vw',103 height: '100vh',104 }}105 >106 <div107 style={{108 position: 'absolute',109 backgroundColor: 'red',110 borderRadius: '50%',111 transform: `translate(${position.x}px, ${position.y}px)`,112 left: -10,113 top: -10,114 width: 20,115 height: 20,116 }}117 />118 </div>119 )120}121```122123Finally, we’ll render the `MovingDot` component in our `App` component.124125```tsx126export default function App() {127 return <MovingDot />128}129```130131Here is what the code should look like:132133```tsx134import { createStore } from 'zustand'135import { useStoreWithEqualityFn } from 'zustand/traditional'136import { shallow } from 'zustand/shallow'137138type PositionStoreState = { position: { x: number; y: number } }139140type PositionStoreActions = {141 setPosition: (nextPosition: PositionStoreState['position']) => void142}143144type PositionStore = PositionStoreState & PositionStoreActions145146const positionStore = createStore<PositionStore>()((set) => ({147 position: { x: 0, y: 0 },148 setPosition: (position) => set({ position }),149}))150151function MovingDot() {152 const position = useStoreWithEqualityFn(153 positionStore,154 (state) => state.position,155 shallow,156 )157 const setPosition = useStoreWithEqualityFn(158 positionStore,159 (state) => state.setPosition,160 shallow,161 )162163 return (164 <div165 onPointerMove={(e) => {166 setPosition({167 x: e.clientX,168 y: e.clientY,169 })170 }}171 style={{172 position: 'relative',173 width: '100vw',174 height: '100vh',175 }}176 >177 <div178 style={{179 position: 'absolute',180 backgroundColor: 'red',181 borderRadius: '50%',182 transform: `translate(${position.x}px, ${position.y}px)`,183 left: -10,184 top: -10,185 width: 20,186 height: 20,187 }}188 />189 </div>190 )191}192193export default function App() {194 return <MovingDot />195}196```197198### Using dynamic global vanilla stores in React199200First, we'll create a factory function that generates a store for managing the counter state.201Each tab will have its own instance of this store.202203```ts204import { createStore } from 'zustand'205206type CounterState = {207 count: number208}209210type CounterActions = { increment: () => void }211212type CounterStore = CounterState & CounterActions213214const createCounterStore = () => {215 return createStore<CounterStore>()((set) => ({216 count: 0,217 increment: () => {218 set((state) => ({ count: state.count + 1 }))219 },220 }))221}222```223224Next, we'll create a factory function that manages the creation and retrieval of counter stores.225This allows each tab to have its own independent counter.226227```ts228const defaultCounterStores = new Map<229 string,230 ReturnType<typeof createCounterStore>231>()232233const createCounterStoreFactory = (234 counterStores: typeof defaultCounterStores,235) => {236 return (counterStoreKey: string) => {237 if (!counterStores.has(counterStoreKey)) {238 counterStores.set(counterStoreKey, createCounterStore())239 }240 return counterStores.get(counterStoreKey)!241 }242}243244const getOrCreateCounterStoreByKey =245 createCounterStoreFactory(defaultCounterStores)246```247248Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s249counter.250251```tsx252const [currentTabIndex, setCurrentTabIndex] = useState(0)253const counterState = useStoreWithEqualityFn(254 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),255 (state) => state,256 shallow,257)258259return (260 <div style={{ fontFamily: 'monospace' }}>261 <div262 style={{263 display: 'flex',264 gap: '0.5rem',265 borderBottom: '1px solid salmon',266 paddingBottom: 4,267 }}268 >269 <button270 type="button"271 style={{272 border: '1px solid salmon',273 backgroundColor: '#fff',274 cursor: 'pointer',275 }}276 onClick={() => setCurrentTabIndex(0)}277 >278 Tab 1279 </button>280 <button281 type="button"282 style={{283 border: '1px solid salmon',284 backgroundColor: '#fff',285 cursor: 'pointer',286 }}287 onClick={() => setCurrentTabIndex(1)}288 >289 Tab 2290 </button>291 <button292 type="button"293 style={{294 border: '1px solid salmon',295 backgroundColor: '#fff',296 cursor: 'pointer',297 }}298 onClick={() => setCurrentTabIndex(2)}299 >300 Tab 3301 </button>302 </div>303 <div style={{ padding: 4 }}>304 Content of Tab {currentTabIndex + 1}305 <br /> <br />306 <button type="button" onClick={() => counterState.increment()}>307 Count: {counterState.count}308 </button>309 </div>310 </div>311)312```313314Finally, we'll create the `App` component, which renders the tabs and their respective counters.315The counter state is managed independently for each tab.316317```tsx318export default function App() {319 return <Tabs />320}321```322323Here is what the code should look like:324325```tsx326import { useState } from 'react'327import { createStore } from 'zustand'328import { useStoreWithEqualityFn } from 'zustand/traditional'329import { shallow } from 'zustand/shallow'330331type CounterState = {332 count: number333}334335type CounterActions = { increment: () => void }336337type CounterStore = CounterState & CounterActions338339const createCounterStore = () => {340 return createStore<CounterStore>()((set) => ({341 count: 0,342 increment: () => {343 set((state) => ({ count: state.count + 1 }))344 },345 }))346}347348const defaultCounterStores = new Map<349 string,350 ReturnType<typeof createCounterStore>351>()352353const createCounterStoreFactory = (354 counterStores: typeof defaultCounterStores,355) => {356 return (counterStoreKey: string) => {357 if (!counterStores.has(counterStoreKey)) {358 counterStores.set(counterStoreKey, createCounterStore())359 }360 return counterStores.get(counterStoreKey)!361 }362}363364const getOrCreateCounterStoreByKey =365 createCounterStoreFactory(defaultCounterStores)366367export default function App() {368 const [currentTabIndex, setCurrentTabIndex] = useState(0)369 const counterState = useStoreWithEqualityFn(370 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),371 (state) => state,372 shallow,373 )374375 return (376 <div style={{ fontFamily: 'monospace' }}>377 <div378 style={{379 display: 'flex',380 gap: '0.5rem',381 borderBottom: '1px solid salmon',382 paddingBottom: 4,383 }}384 >385 <button386 type="button"387 style={{388 border: '1px solid salmon',389 backgroundColor: '#fff',390 cursor: 'pointer',391 }}392 onClick={() => setCurrentTabIndex(0)}393 >394 Tab 1395 </button>396 <button397 type="button"398 style={{399 border: '1px solid salmon',400 backgroundColor: '#fff',401 cursor: 'pointer',402 }}403 onClick={() => setCurrentTabIndex(1)}404 >405 Tab 2406 </button>407 <button408 type="button"409 style={{410 border: '1px solid salmon',411 backgroundColor: '#fff',412 cursor: 'pointer',413 }}414 onClick={() => setCurrentTabIndex(2)}415 >416 Tab 3417 </button>418 </div>419 <div style={{ padding: 4 }}>420 Content of Tab {currentTabIndex + 1}421 <br /> <br />422 <button type="button" onClick={() => counterState.increment()}>423 Count: {counterState.count}424 </button>425 </div>426 </div>427 )428}429```430431### Using scoped (non-global) vanilla store in React432433First, let's set up a store that will hold the position of the dot on the screen. We'll define the434store to manage `x` and `y` coordinates and provide an action to update these coordinates.435436```tsx437type PositionStoreState = { position: { x: number; y: number } }438439type PositionStoreActions = {440 setPosition: (nextPosition: PositionStoreState['position']) => void441}442443type PositionStore = PositionStoreState & PositionStoreActions444445const createPositionStore = () => {446 return createStore<PositionStore>()((set) => ({447 position: { x: 0, y: 0 },448 setPosition: (position) => set({ position }),449 }))450}451```452453Next, we'll create a context and a provider component to pass down the store through the React454component tree. This allows each `MovingDot` component to have its own independent state.455456```tsx457const PositionStoreContext = createContext<ReturnType<458 typeof createPositionStore459> | null>(null)460461function PositionStoreProvider({ children }: { children: ReactNode }) {462 const [store] = useState(() => createPositionStore())463 return (464 <PositionStoreContext.Provider value={store}>465 {children}466 </PositionStoreContext.Provider>467 )468}469```470471To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook472will read the store from the context and allow us to select specific parts of the state.473474```ts475function usePositionStore<U>(selector: (state: PositionStore) => U) {476 const store = useContext(PositionStoreContext)477478 if (store === null) {479 throw new Error(480 'usePositionStore must be used within PositionStoreProvider',481 )482 }483484 return useStoreWithEqualityFn(store, selector, shallow)485}486```487488Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor489within its container.490491```tsx492function MovingDot({ color }: { color: string }) {493 const position = usePositionStore((state) => state.position)494 const setPosition = usePositionStore((state) => state.setPosition)495496 return (497 <div498 onPointerMove={(e) => {499 setPosition({500 x:501 e.clientX > e.currentTarget.clientWidth502 ? e.clientX - e.currentTarget.clientWidth503 : e.clientX,504 y: e.clientY,505 })506 }}507 style={{508 position: 'relative',509 width: '50vw',510 height: '100vh',511 }}512 >513 <div514 style={{515 position: 'absolute',516 backgroundColor: color,517 borderRadius: '50%',518 transform: `translate(${position.x}px, ${position.y}px)`,519 left: -10,520 top: -10,521 width: 20,522 height: 20,523 }}524 />525 </div>526 )527}528```529530Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`531components, each with its own independent state.532533```tsx534export default function App() {535 return (536 <div style={{ display: 'flex' }}>537 <PositionStoreProvider>538 <MovingDot color="red" />539 </PositionStoreProvider>540 <PositionStoreProvider>541 <MovingDot color="blue" />542 </PositionStoreProvider>543 </div>544 )545}546```547548Here is what the code should look like:549550```tsx551import { type ReactNode, useState, createContext, useContext } from 'react'552import { createStore } from 'zustand'553import { useStoreWithEqualityFn } from 'zustand/traditional'554import { shallow } from 'zustand/shallow'555556type PositionStoreState = { position: { x: number; y: number } }557558type PositionStoreActions = {559 setPosition: (nextPosition: PositionStoreState['position']) => void560}561562type PositionStore = PositionStoreState & PositionStoreActions563564const createPositionStore = () => {565 return createStore<PositionStore>()((set) => ({566 position: { x: 0, y: 0 },567 setPosition: (position) => set({ position }),568 }))569}570571const PositionStoreContext = createContext<ReturnType<572 typeof createPositionStore573> | null>(null)574575function PositionStoreProvider({ children }: { children: ReactNode }) {576 const [store] = useState(() => createPositionStore())577 return (578 <PositionStoreContext.Provider value={store}>579 {children}580 </PositionStoreContext.Provider>581 )582}583584function usePositionStore<U>(selector: (state: PositionStore) => U) {585 const store = useContext(PositionStoreContext)586587 if (store === null) {588 throw new Error(589 'usePositionStore must be used within PositionStoreProvider',590 )591 }592593 return useStoreWithEqualityFn(store, selector, shallow)594}595596function MovingDot({ color }: { color: string }) {597 const position = usePositionStore((state) => state.position)598 const setPosition = usePositionStore((state) => state.setPosition)599600 return (601 <div602 onPointerMove={(e) => {603 setPosition({604 x:605 e.clientX > e.currentTarget.clientWidth606 ? e.clientX - e.currentTarget.clientWidth607 : e.clientX,608 y: e.clientY,609 })610 }}611 style={{612 position: 'relative',613 width: '50vw',614 height: '100vh',615 }}616 >617 <div618 style={{619 position: 'absolute',620 backgroundColor: color,621 borderRadius: '50%',622 transform: `translate(${position.x}px, ${position.y}px)`,623 left: -10,624 top: -10,625 width: 20,626 height: 20,627 }}628 />629 </div>630 )631}632633export default function App() {634 return (635 <div style={{ display: 'flex' }}>636 <PositionStoreProvider>637 <MovingDot color="red" />638 </PositionStoreProvider>639 <PositionStoreProvider>640 <MovingDot color="blue" />641 </PositionStoreProvider>642 </div>643 )644}645```646647### Using dynamic scoped (non-global) vanilla stores in React648649First, we'll create a factory function that generates a store for managing the counter state.650Each tab will have its own instance of this store.651652```ts653type CounterState = {654 count: number655}656657type CounterActions = { increment: () => void }658659type CounterStore = CounterState & CounterActions660661const createCounterStore = () => {662 return createStore<CounterStore>()((set) => ({663 count: 0,664 increment: () => {665 set((state) => ({ count: state.count + 1 }))666 },667 }))668}669```670671Next, we'll create a factory function that manages the creation and retrieval of counter stores.672This allows each tab to have its own independent counter.673674```ts675const createCounterStoreFactory = (676 counterStores: Map<string, ReturnType<typeof createCounterStore>>,677) => {678 return (counterStoreKey: string) => {679 if (!counterStores.has(counterStoreKey)) {680 counterStores.set(counterStoreKey, createCounterStore())681 }682 return counterStores.get(counterStoreKey)!683 }684}685```686687Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context688for this.689690```tsx691const CounterStoresContext = createContext(null)692693const CounterStoresProvider = ({ children }) => {694 const [stores] = useState(695 () => new Map<string, ReturnType<typeof createCounterStore>>(),696 )697698 return (699 <CounterStoresContext.Provider value={stores}>700 {children}701 </CounterStoresContext.Provider>702 )703}704```705706Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a707given tab.708709```tsx710const useCounterStore = <U,>(711 key: string,712 selector: (state: CounterStore) => U,713) => {714 const stores = useContext(CounterStoresContext)715716 if (stores === undefined) {717 throw new Error('useCounterStore must be used within CounterStoresProvider')718 }719720 const getOrCreateCounterStoreByKey = useCallback(721 (key: string) => createCounterStoreFactory(stores!)(key),722 [stores],723 )724725 return useStore(getOrCreateCounterStoreByKey(key), selector)726}727```728729Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s730counter.731732```tsx733function Tabs() {734 const [currentTabIndex, setCurrentTabIndex] = useState(0)735 const counterState = useCounterStore(736 `tab-${currentTabIndex}`,737 (state) => state,738 )739740 return (741 <div style={{ fontFamily: 'monospace' }}>742 <div743 style={{744 display: 'flex',745 gap: '0.5rem',746 borderBottom: '1px solid salmon',747 paddingBottom: 4,748 }}749 >750 <button751 type="button"752 style={{753 border: '1px solid salmon',754 backgroundColor: '#fff',755 cursor: 'pointer',756 }}757 onClick={() => setCurrentTabIndex(0)}758 >759 Tab 1760 </button>761 <button762 type="button"763 style={{764 border: '1px solid salmon',765 backgroundColor: '#fff',766 cursor: 'pointer',767 }}768 onClick={() => setCurrentTabIndex(1)}769 >770 Tab 2771 </button>772 <button773 type="button"774 style={{775 border: '1px solid salmon',776 backgroundColor: '#fff',777 cursor: 'pointer',778 }}779 onClick={() => setCurrentTabIndex(2)}780 >781 Tab 3782 </button>783 </div>784 <div style={{ padding: 4 }}>785 Content of Tab {currentTabIndex + 1}786 <br /> <br />787 <button type="button" onClick={() => counterState.increment()}>788 Count: {counterState.count}789 </button>790 </div>791 </div>792 )793}794```795796Finally, we'll create the `App` component, which renders the tabs and their respective counters.797The counter state is managed independently for each tab.798799```tsx800export default function App() {801 return (802 <CounterStoresProvider>803 <Tabs />804 </CounterStoresProvider>805 )806}807```808809Here is what the code should look like:810811```tsx812import {813 type ReactNode,814 useState,815 useCallback,816 useContext,817 createContext,818} from 'react'819import { createStore, useStore } from 'zustand'820821type CounterState = {822 count: number823}824825type CounterActions = { increment: () => void }826827type CounterStore = CounterState & CounterActions828829const createCounterStore = () => {830 return createStore<CounterStore>()((set) => ({831 count: 0,832 increment: () => {833 set((state) => ({ count: state.count + 1 }))834 },835 }))836}837838const createCounterStoreFactory = (839 counterStores: Map<string, ReturnType<typeof createCounterStore>>,840) => {841 return (counterStoreKey: string) => {842 if (!counterStores.has(counterStoreKey)) {843 counterStores.set(counterStoreKey, createCounterStore())844 }845 return counterStores.get(counterStoreKey)!846 }847}848849const CounterStoresContext = createContext<Map<850 string,851 ReturnType<typeof createCounterStore>852> | null>(null)853854const CounterStoresProvider = ({ children }: { children: ReactNode }) => {855 const [stores] = useState(856 () => new Map<string, ReturnType<typeof createCounterStore>>(),857 )858859 return (860 <CounterStoresContext.Provider value={stores}>861 {children}862 </CounterStoresContext.Provider>863 )864}865866const useCounterStore = <U,>(867 key: string,868 selector: (state: CounterStore) => U,869) => {870 const stores = useContext(CounterStoresContext)871872 if (stores === undefined) {873 throw new Error('useCounterStore must be used within CounterStoresProvider')874 }875876 const getOrCreateCounterStoreByKey = useCallback(877 (key: string) => createCounterStoreFactory(stores!)(key),878 [stores],879 )880881 return useStore(getOrCreateCounterStoreByKey(key), selector)882}883884function Tabs() {885 const [currentTabIndex, setCurrentTabIndex] = useState(0)886 const counterState = useCounterStore(887 `tab-${currentTabIndex}`,888 (state) => state,889 )890891 return (892 <div style={{ fontFamily: 'monospace' }}>893 <div894 style={{895 display: 'flex',896 gap: '0.5rem',897 borderBottom: '1px solid salmon',898 paddingBottom: 4,899 }}900 >901 <button902 type="button"903 style={{904 border: '1px solid salmon',905 backgroundColor: '#fff',906 cursor: 'pointer',907 }}908 onClick={() => setCurrentTabIndex(0)}909 >910 Tab 1911 </button>912 <button913 type="button"914 style={{915 border: '1px solid salmon',916 backgroundColor: '#fff',917 cursor: 'pointer',918 }}919 onClick={() => setCurrentTabIndex(1)}920 >921 Tab 2922 </button>923 <button924 type="button"925 style={{926 border: '1px solid salmon',927 backgroundColor: '#fff',928 cursor: 'pointer',929 }}930 onClick={() => setCurrentTabIndex(2)}931 >932 Tab 3933 </button>934 </div>935 <div style={{ padding: 4 }}>936 Content of Tab {currentTabIndex + 1}937 <br /> <br />938 <button type="button" onClick={() => counterState.increment()}>939 Count: {counterState.count}940 </button>941 </div>942 </div>943 )944}945946export default function App() {947 return (948 <CounterStoresProvider>949 <Tabs />950 </CounterStoresProvider>951 )952}953```954955## Troubleshooting956957TBD
added:docs/reference/hooks/use-store.md+923 added
1---2title: useStore3description: How to use vanilla stores in React4tag: react5nav: 256---78`useStore` is a React Hook that lets you use a vanilla store in React.910```js11const someState = useStore(store, selectorFn)12```1314- [Types](#types)15 - [Signature](#signature)16- [Reference](#reference)17- [Usage](#usage)18 - [Use a vanilla store in React](#use-a-vanilla-store-in-react)19 - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)20 - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)21 - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)22- [Troubleshooting](#troubleshooting)2324## Types2526### Signature2728```ts29useStore<StoreApi<T>, U = T>(store: StoreApi<T>, selectorFn?: (state: T) => U) => UseBoundStore<StoreApi<T>>30```3132## Reference3334### `useStore(store, selectorFn)`3536#### Parameters3738- `storeApi`: The instance that lets you access to store API utilities.39- `selectorFn`: A function that lets you return data that is based on current state.4041#### Returns4243`useStore` returns any data based on current state depending on the selector function. It should44take a store, and a selector function as arguments.4546## Usage4748### Using a global vanilla store in React4950First, let's set up a store that will hold the position of the dot on the screen. We'll define the51store to manage `x` and `y` coordinates and provide an action to update these coordinates.5253```tsx54type PositionStoreState = { position: { x: number; y: number } }5556type PositionStoreActions = {57 setPosition: (nextPosition: PositionStoreState['position']) => void58}5960type PositionStore = PositionStoreState & PositionStoreActions6162const positionStore = createStore<PositionStore>()((set) => ({63 position: { x: 0, y: 0 },64 setPosition: (position) => set({ position }),65}))66```6768Next, we'll create a `MovingDot` component that renders a div representing the dot. This component69will use the store to track and update the dot's position.7071```tsx72function MovingDot() {73 const position = useStore(positionStore, (state) => state.position)74 const setPosition = useStore(positionStore, (state) => state.setPosition)7576 return (77 <div78 onPointerMove={(e) => {79 setPosition({80 x: e.clientX,81 y: e.clientY,82 })83 }}84 style={{85 position: 'relative',86 width: '100vw',87 height: '100vh',88 }}89 >90 <div91 style={{92 position: 'absolute',93 backgroundColor: 'red',94 borderRadius: '50%',95 transform: `translate(${position.x}px, ${position.y}px)`,96 left: -10,97 top: -10,98 width: 20,99 height: 20,100 }}101 />102 </div>103 )104}105```106107Finally, we’ll render the `MovingDot` component in our `App` component.108109```tsx110export default function App() {111 return <MovingDot />112}113```114115Here is what the code should look like:116117```tsx118import { createStore, useStore } from 'zustand'119120type PositionStoreState = { position: { x: number; y: number } }121122type PositionStoreActions = {123 setPosition: (nextPosition: PositionStoreState['position']) => void124}125126type PositionStore = PositionStoreState & PositionStoreActions127128const positionStore = createStore<PositionStore>()((set) => ({129 position: { x: 0, y: 0 },130 setPosition: (position) => set({ position }),131}))132133function MovingDot() {134 const position = useStore(positionStore, (state) => state.position)135 const setPosition = useStore(positionStore, (state) => state.setPosition)136137 return (138 <div139 onPointerMove={(e) => {140 setPosition({141 x: e.clientX,142 y: e.clientY,143 })144 }}145 style={{146 position: 'relative',147 width: '100vw',148 height: '100vh',149 }}150 >151 <div152 style={{153 position: 'absolute',154 backgroundColor: 'red',155 borderRadius: '50%',156 transform: `translate(${position.x}px, ${position.y}px)`,157 left: -10,158 top: -10,159 width: 20,160 height: 20,161 }}162 />163 </div>164 )165}166167export default function App() {168 return <MovingDot />169}170```171172### Using dynamic global vanilla stores in React173174First, we'll create a factory function that generates a store for managing the counter state.175Each tab will have its own instance of this store.176177```ts178type CounterState = {179 count: number180}181182type CounterActions = { increment: () => void }183184type CounterStore = CounterState & CounterActions185186const createCounterStore = () => {187 return createStore<CounterStore>()((set) => ({188 count: 0,189 increment: () => {190 set((state) => ({ count: state.count + 1 }))191 },192 }))193}194```195196Next, we'll create a factory function that manages the creation and retrieval of counter stores.197This allows each tab to have its own independent counter.198199```ts200const defaultCounterStores = new Map<201 string,202 ReturnType<typeof createCounterStore>203>()204205const createCounterStoreFactory = (206 counterStores: typeof defaultCounterStores,207) => {208 return (counterStoreKey: string) => {209 if (!counterStores.has(counterStoreKey)) {210 counterStores.set(counterStoreKey, createCounterStore())211 }212 return counterStores.get(counterStoreKey)!213 }214}215216const getOrCreateCounterStoreByKey =217 createCounterStoreFactory(defaultCounterStores)218```219220Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s221counter.222223```tsx224const [currentTabIndex, setCurrentTabIndex] = useState(0)225const counterState = useStore(226 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),227)228229return (230 <div style={{ fontFamily: 'monospace' }}>231 <div232 style={{233 display: 'flex',234 gap: '0.5rem',235 borderBottom: '1px solid salmon',236 paddingBottom: 4,237 }}238 >239 <button240 type="button"241 style={{242 border: '1px solid salmon',243 backgroundColor: '#fff',244 cursor: 'pointer',245 }}246 onClick={() => setCurrentTabIndex(0)}247 >248 Tab 1249 </button>250 <button251 type="button"252 style={{253 border: '1px solid salmon',254 backgroundColor: '#fff',255 cursor: 'pointer',256 }}257 onClick={() => setCurrentTabIndex(1)}258 >259 Tab 2260 </button>261 <button262 type="button"263 style={{264 border: '1px solid salmon',265 backgroundColor: '#fff',266 cursor: 'pointer',267 }}268 onClick={() => setCurrentTabIndex(2)}269 >270 Tab 3271 </button>272 </div>273 <div style={{ padding: 4 }}>274 Content of Tab {currentTabIndex + 1}275 <br /> <br />276 <button type="button" onClick={() => counterState.increment()}>277 Count: {counterState.count}278 </button>279 </div>280 </div>281)282```283284Finally, we'll create the `App` component, which renders the tabs and their respective counters.285The counter state is managed independently for each tab.286287```tsx288export default function App() {289 return <Tabs />290}291```292293Here is what the code should look like:294295```tsx296import { useState } from 'react'297import { createStore, useStore } from 'zustand'298299type CounterState = {300 count: number301}302303type CounterActions = { increment: () => void }304305type CounterStore = CounterState & CounterActions306307const createCounterStore = () => {308 return createStore<CounterStore>()((set) => ({309 count: 0,310 increment: () => {311 set((state) => ({ count: state.count + 1 }))312 },313 }))314}315316const defaultCounterStores = new Map<317 string,318 ReturnType<typeof createCounterStore>319>()320321const createCounterStoreFactory = (322 counterStores: typeof defaultCounterStores,323) => {324 return (counterStoreKey: string) => {325 if (!counterStores.has(counterStoreKey)) {326 counterStores.set(counterStoreKey, createCounterStore())327 }328 return counterStores.get(counterStoreKey)!329 }330}331332const getOrCreateCounterStoreByKey =333 createCounterStoreFactory(defaultCounterStores)334335export default function App() {336 const [currentTabIndex, setCurrentTabIndex] = useState(0)337 const counterState = useStore(338 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),339 )340341 return (342 <div style={{ fontFamily: 'monospace' }}>343 <div344 style={{345 display: 'flex',346 gap: '0.5rem',347 borderBottom: '1px solid salmon',348 paddingBottom: 4,349 }}350 >351 <button352 type="button"353 style={{354 border: '1px solid salmon',355 backgroundColor: '#fff',356 cursor: 'pointer',357 }}358 onClick={() => setCurrentTabIndex(0)}359 >360 Tab 1361 </button>362 <button363 type="button"364 style={{365 border: '1px solid salmon',366 backgroundColor: '#fff',367 cursor: 'pointer',368 }}369 onClick={() => setCurrentTabIndex(1)}370 >371 Tab 2372 </button>373 <button374 type="button"375 style={{376 border: '1px solid salmon',377 backgroundColor: '#fff',378 cursor: 'pointer',379 }}380 onClick={() => setCurrentTabIndex(2)}381 >382 Tab 3383 </button>384 </div>385 <div style={{ padding: 4 }}>386 Content of Tab {currentTabIndex + 1}387 <br /> <br />388 <button type="button" onClick={() => counterState.increment()}>389 Count: {counterState.count}390 </button>391 </div>392 </div>393 )394}395```396397### Using scoped (non-global) vanilla store in React398399First, let's set up a store that will hold the position of the dot on the screen. We'll define the400store to manage `x` and `y` coordinates and provide an action to update these coordinates.401402```tsx403type PositionStoreState = { position: { x: number; y: number } }404405type PositionStoreActions = {406 setPosition: (nextPosition: PositionStoreState['position']) => void407}408409type PositionStore = PositionStoreState & PositionStoreActions410411const createPositionStore = () => {412 return createStore<PositionStore>()((set) => ({413 position: { x: 0, y: 0 },414 setPosition: (position) => set({ position }),415 }))416}417```418419Next, we'll create a context and a provider component to pass down the store through the React420component tree. This allows each `MovingDot` component to have its own independent state.421422```tsx423const PositionStoreContext = createContext<ReturnType<424 typeof createPositionStore425> | null>(null)426427function PositionStoreProvider({ children }: { children: ReactNode }) {428 const [store] = useState(() => createPositionStore())429 return (430 <PositionStoreContext.Provider value={store}>431 {children}432 </PositionStoreContext.Provider>433 )434}435```436437To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook438will read the store from the context and allow us to select specific parts of the state.439440```ts441function usePositionStore<U>(selector: (state: PositionStore) => U) {442 const store = useContext(PositionStoreContext)443444 if (store === null) {445 throw new Error(446 'usePositionStore must be used within PositionStoreProvider',447 )448 }449450 return useStore(store, selector)451}452```453454Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor455within its container.456457```tsx458function MovingDot({ color }: { color: string }) {459 const position = usePositionStore((state) => state.position)460 const setPosition = usePositionStore((state) => state.setPosition)461462 return (463 <div464 onPointerMove={(e) => {465 setPosition({466 x:467 e.clientX > e.currentTarget.clientWidth468 ? e.clientX - e.currentTarget.clientWidth469 : e.clientX,470 y: e.clientY,471 })472 }}473 style={{474 position: 'relative',475 width: '50vw',476 height: '100vh',477 }}478 >479 <div480 style={{481 position: 'absolute',482 backgroundColor: color,483 borderRadius: '50%',484 transform: `translate(${position.x}px, ${position.y}px)`,485 left: -10,486 top: -10,487 width: 20,488 height: 20,489 }}490 />491 </div>492 )493}494```495496Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`497components, each with its own independent state.498499```tsx500export default function App() {501 return (502 <div style={{ display: 'flex' }}>503 <PositionStoreProvider>504 <MovingDot color="red" />505 </PositionStoreProvider>506 <PositionStoreProvider>507 <MovingDot color="blue" />508 </PositionStoreProvider>509 </div>510 )511}512```513514Here is what the code should look like:515516```tsx517import { type ReactNode, useState, createContext, useContext } from 'react'518import { createStore, useStore } from 'zustand'519520type PositionStoreState = { position: { x: number; y: number } }521522type PositionStoreActions = {523 setPosition: (nextPosition: PositionStoreState['position']) => void524}525526type PositionStore = PositionStoreState & PositionStoreActions527528const createPositionStore = () => {529 return createStore<PositionStore>()((set) => ({530 position: { x: 0, y: 0 },531 setPosition: (position) => set({ position }),532 }))533}534535const PositionStoreContext = createContext<ReturnType<536 typeof createPositionStore537> | null>(null)538539function PositionStoreProvider({ children }: { children: ReactNode }) {540 const [store] = useState(() => createPositionStore())541 return (542 <PositionStoreContext.Provider value={store}>543 {children}544 </PositionStoreContext.Provider>545 )546}547548function usePositionStore<U>(selector: (state: PositionStore) => U) {549 const store = useContext(PositionStoreContext)550551 if (store === null) {552 throw new Error(553 'usePositionStore must be used within PositionStoreProvider',554 )555 }556557 return useStore(store, selector)558}559560function MovingDot({ color }: { color: string }) {561 const position = usePositionStore((state) => state.position)562 const setPosition = usePositionStore((state) => state.setPosition)563564 return (565 <div566 onPointerMove={(e) => {567 setPosition({568 x:569 e.clientX > e.currentTarget.clientWidth570 ? e.clientX - e.currentTarget.clientWidth571 : e.clientX,572 y: e.clientY,573 })574 }}575 style={{576 position: 'relative',577 width: '50vw',578 height: '100vh',579 }}580 >581 <div582 style={{583 position: 'absolute',584 backgroundColor: color,585 borderRadius: '50%',586 transform: `translate(${position.x}px, ${position.y}px)`,587 left: -10,588 top: -10,589 width: 20,590 height: 20,591 }}592 />593 </div>594 )595}596597export default function App() {598 return (599 <div style={{ display: 'flex' }}>600 <PositionStoreProvider>601 <MovingDot color="red" />602 </PositionStoreProvider>603 <PositionStoreProvider>604 <MovingDot color="blue" />605 </PositionStoreProvider>606 </div>607 )608}609```610611### Using dynamic scoped (non-global) vanilla stores in React612613First, we'll create a factory function that generates a store for managing the counter state.614Each tab will have its own instance of this store.615616```ts617import { createStore } from 'zustand'618619type CounterState = {620 count: number621}622623type CounterActions = { increment: () => void }624625type CounterStore = CounterState & CounterActions626627const createCounterStore = () => {628 return createStore<CounterStore>()((set) => ({629 count: 0,630 increment: () => {631 set((state) => ({ count: state.count + 1 }))632 },633 }))634}635```636637Next, we'll create a factory function that manages the creation and retrieval of counter stores.638This allows each tab to have its own independent counter.639640```ts641const createCounterStoreFactory = (642 counterStores: Map<string, ReturnType<typeof createCounterStore>>,643) => {644 return (counterStoreKey: string) => {645 if (!counterStores.has(counterStoreKey)) {646 counterStores.set(counterStoreKey, createCounterStore())647 }648 return counterStores.get(counterStoreKey)!649 }650}651```652653Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context654for this.655656```tsx657const CounterStoresContext = createContext(null)658659const CounterStoresProvider = ({ children }) => {660 const [stores] = useState(661 () => new Map<string, ReturnType<typeof createCounterStore>>(),662 )663664 return (665 <CounterStoresContext.Provider value={stores}>666 {children}667 </CounterStoresContext.Provider>668 )669}670```671672Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a673given tab.674675```tsx676const useCounterStore = <U>(677 currentTabIndex: number,678 selector: (state: CounterStore) => U,679) => {680 const stores = useContext(CounterStoresContext)681682 if (stores === undefined) {683 throw new Error('useCounterStore must be used within CounterStoresProvider')684 }685686 const getOrCreateCounterStoreByKey = useCallback(687 () => createCounterStoreFactory(stores),688 [stores],689 )690691 return useStore(getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`))692}693```694695Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s696counter.697698```tsx699function Tabs() {700 const [currentTabIndex, setCurrentTabIndex] = useState(0)701 const counterState = useCounterStore(702 `tab-${currentTabIndex}`,703 (state) => state,704 )705706 return (707 <div style={{ fontFamily: 'monospace' }}>708 <div709 style={{710 display: 'flex',711 gap: '0.5rem',712 borderBottom: '1px solid salmon',713 paddingBottom: 4,714 }}715 >716 <button717 type="button"718 style={{719 border: '1px solid salmon',720 backgroundColor: '#fff',721 cursor: 'pointer',722 }}723 onClick={() => setCurrentTabIndex(0)}724 >725 Tab 1726 </button>727 <button728 type="button"729 style={{730 border: '1px solid salmon',731 backgroundColor: '#fff',732 cursor: 'pointer',733 }}734 onClick={() => setCurrentTabIndex(1)}735 >736 Tab 2737 </button>738 <button739 type="button"740 style={{741 border: '1px solid salmon',742 backgroundColor: '#fff',743 cursor: 'pointer',744 }}745 onClick={() => setCurrentTabIndex(2)}746 >747 Tab 3748 </button>749 </div>750 <div style={{ padding: 4 }}>751 Content of Tab {currentTabIndex + 1}752 <br /> <br />753 <button type="button" onClick={() => counterState.increment()}>754 Count: {counterState.count}755 </button>756 </div>757 </div>758 )759}760```761762Finally, we'll create the `App` component, which renders the tabs and their respective counters.763The counter state is managed independently for each tab.764765```tsx766export default function App() {767 return (768 <CounterStoresProvider>769 <Tabs />770 </CounterStoresProvider>771 )772}773```774775Here is what the code should look like:776777```tsx778import {779 type ReactNode,780 useState,781 useCallback,782 useContext,783 createContext,784} from 'react'785import { createStore, useStore } from 'zustand'786787type CounterState = {788 count: number789}790791type CounterActions = { increment: () => void }792793type CounterStore = CounterState & CounterActions794795const createCounterStore = () => {796 return createStore<CounterStore>()((set) => ({797 count: 0,798 increment: () => {799 set((state) => ({ count: state.count + 1 }))800 },801 }))802}803804const createCounterStoreFactory = (805 counterStores: Map<string, ReturnType<typeof createCounterStore>>,806) => {807 return (counterStoreKey: string) => {808 if (!counterStores.has(counterStoreKey)) {809 counterStores.set(counterStoreKey, createCounterStore())810 }811 return counterStores.get(counterStoreKey)!812 }813}814815const CounterStoresContext = createContext<Map<816 string,817 ReturnType<typeof createCounterStore>818> | null>(null)819820const CounterStoresProvider = ({ children }: { children: ReactNode }) => {821 const [stores] = useState(822 () => new Map<string, ReturnType<typeof createCounterStore>>(),823 )824825 return (826 <CounterStoresContext.Provider value={stores}>827 {children}828 </CounterStoresContext.Provider>829 )830}831832const useCounterStore = <U,>(833 key: string,834 selector: (state: CounterStore) => U,835) => {836 const stores = useContext(CounterStoresContext)837838 if (stores === undefined) {839 throw new Error('useCounterStore must be used within CounterStoresProvider')840 }841842 const getOrCreateCounterStoreByKey = useCallback(843 (key: string) => createCounterStoreFactory(stores!)(key),844 [stores],845 )846847 return useStore(getOrCreateCounterStoreByKey(key), selector)848}849850function Tabs() {851 const [currentTabIndex, setCurrentTabIndex] = useState(0)852 const counterState = useCounterStore(853 `tab-${currentTabIndex}`,854 (state) => state,855 )856857 return (858 <div style={{ fontFamily: 'monospace' }}>859 <div860 style={{861 display: 'flex',862 gap: '0.5rem',863 borderBottom: '1px solid salmon',864 paddingBottom: 4,865 }}866 >867 <button868 type="button"869 style={{870 border: '1px solid salmon',871 backgroundColor: '#fff',872 cursor: 'pointer',873 }}874 onClick={() => setCurrentTabIndex(0)}875 >876 Tab 1877 </button>878 <button879 type="button"880 style={{881 border: '1px solid salmon',882 backgroundColor: '#fff',883 cursor: 'pointer',884 }}885 onClick={() => setCurrentTabIndex(1)}886 >887 Tab 2888 </button>889 <button890 type="button"891 style={{892 border: '1px solid salmon',893 backgroundColor: '#fff',894 cursor: 'pointer',895 }}896 onClick={() => setCurrentTabIndex(2)}897 >898 Tab 3899 </button>900 </div>901 <div style={{ padding: 4 }}>902 Content of Tab {currentTabIndex + 1}903 <br /> <br />904 <button type="button" onClick={() => counterState.increment()}>905 Count: {counterState.count}906 </button>907 </div>908 </div>909 )910}911912export default function App() {913 return (914 <CounterStoresProvider>915 <Tabs />916 </CounterStoresProvider>917 )918}919```920921## Troubleshooting922923TBD
added:docs/reference/integrations/immer-middleware.md+129 added
1---2title: Immer middleware3nav: 354---56The [Immer](https://github.com/immerjs/immer) middleware enables you7to use immutable state in a more convenient way.8Also, with Immer, you can simplify handling9immutable data structures in Zustand.1011## Installation1213In order to use the Immer middleware in Zustand,14you will need to install Immer as a direct dependency.1516```bash17npm install immer18```1920## Usage2122(Notice the extra parentheses after the type parameter as mentioned in the [Advanced Typescript Guide](../../learn/guides/advanced-typescript.md)).2324Updating simple states2526```ts27import { create } from 'zustand'28import { immer } from 'zustand/middleware/immer'2930type State = {31 count: number32}3334type Actions = {35 increment: (qty: number) => void36 decrement: (qty: number) => void37}3839export const useCountStore = create<State & Actions>()(40 immer((set) => ({41 count: 0,42 increment: (qty: number) =>43 set((state) => {44 state.count += qty45 }),46 decrement: (qty: number) =>47 set((state) => {48 state.count -= qty49 }),50 })),51)52```5354Updating complex states5556```ts57import { create } from 'zustand'58import { immer } from 'zustand/middleware/immer'5960interface Todo {61 id: string62 title: string63 done: boolean64}6566type State = {67 todos: Record<string, Todo>68}6970type Actions = {71 toggleTodo: (todoId: string) => void72}7374export const useTodoStore = create<State & Actions>()(75 immer((set) => ({76 todos: {77 '82471c5f-4207-4b1d-abcb-b98547e01a3e': {78 id: '82471c5f-4207-4b1d-abcb-b98547e01a3e',79 title: 'Learn Zustand',80 done: false,81 },82 '354ee16c-bfdd-44d3-afa9-e93679bda367': {83 id: '354ee16c-bfdd-44d3-afa9-e93679bda367',84 title: 'Learn Jotai',85 done: false,86 },87 '771c85c5-46ea-4a11-8fed-36cc2c7be344': {88 id: '771c85c5-46ea-4a11-8fed-36cc2c7be344',89 title: 'Learn Valtio',90 done: false,91 },92 '363a4bac-083f-47f7-a0a2-aeeee153a99c': {93 id: '363a4bac-083f-47f7-a0a2-aeeee153a99c',94 title: 'Learn Signals',95 done: false,96 },97 },98 toggleTodo: (todoId: string) =>99 set((state) => {100 state.todos[todoId].done = !state.todos[todoId].done101 }),102 })),103)104```105106## Gotchas107108In this section you will find some things109that you need to keep in mind when using Zustand with Immer.110111### My subscriptions aren't being called112113If you are using Immer,114make sure you are actually following115[the rules of Immer](https://immerjs.github.io/immer/pitfalls).116117For example, you have to add `[immerable] = true` for118[class objects](https://immerjs.github.io/immer/complex-objects) to work.119If you don't do this, Immer will still mutate the object,120but not as a proxy, so it will also update the current state.121Zustand checks if the state has actually changed,122so since both the current state and the next state are123equal (if you don't do it correctly),124Zustand will skip calling the subscriptions.125126## Demos127128- Basic: https://stackblitz.com/edit/vitejs-vite-3sgc4ejy129- Advanced: https://stackblitz.com/edit/vitejs-vite-jxxtuyj3
added:docs/reference/integrations/persisting-store-data.md+834 added
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```
added:docs/reference/integrations/third-party-libraries.md+82 added
1---2title: Third-party Libraries3nav: 364---56Zustand provides bear necessities for state management.7Although it is great for most projects,8some users wish to extend the library's feature set.9This can be done using third-party libraries created by the community.1011> Disclaimer: These libraries may have bugs, limited maintenance,12> or other limitations, and are not officially recommended13> by pmndrs or the Zustand maintainers.14> This list aims to provide a good starting point15> for someone looking to extend Zustand's feature set.1617- [@colorfy-software/zfy](https://colorfy-software.gitbook.io/zfy/) — 🧸 Useful helpers for state management in React with Zustand.18- [@csark0812/zustand-expo-devtools](https://github.com/csark0812/zustand-expo-devtools) — 🧭 Connect Zustand to Redux DevTools in Expo + React Native using the official Expo DevTools plugin system.19- [@csark0812/zustand-getters](https://github.com/csark0812/zustand-getters) — 🔄 Make JavaScript object getters reactive in Zustand stores — define derived values with `get propertyName()` and they automatically trigger subscription updates when accessed.20- [@davstack/store](https://www.npmjs.com/package/@davstack/store) — A zustand store factory that auto generates selectors with get/set/use methods, supports inferred types, and makes global / local state management easy.21- [@dhmk/zustand-lens](https://github.com/dhmk083/dhmk-zustand-lens) — Lens support for Zustand.22- [@hpkv/zustand-multiplayer](https://github.com/hpkv-io/zustand-multiplayer/tree/main/packages/zustand-multiplayer) — HPKV multiplayer middleware for building realtime collaborative applications23- [@liveblocks/zustand](https://github.com/liveblocks/liveblocks/tree/main/packages/liveblocks-zustand) — Liveblocks middleware to make your application multiplayer.24- [@prncss-xyz/zustand-optics](https://github.com/prncss-xyz/zustand-optics) — An adapter for [optics-ts](https://github.com/akheron/optics-ts).25- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook) — Automatic generation of Zustand hooks with Typescript support.26- [derive-zustand](https://github.com/zustandjs/derive-zustand) — A function to create a derived Zustand store from other Zustand stores.27- [geschichte](https://github.com/BowlingX/geschichte) — Zustand and Immer-based hook to manage query parameters.28- [leiten-zustand](https://github.com/hecmatyar/leiten-zustand) — Cleans your store from boilerplate for requests and data transformation.29- [leo-query](https://github.com/steaks/leo-query) — A simple library to connect async queries to Zustand stores.30- [mobz](https://github.com/2A5F/Mobz) — Zustand-style MobX API.31- [ngx-zustand](https://github.com/JoaoPauloLousada/ngx-zustand) — A Zustand adapter for Angular.32- [persist-and-sync](https://github.com/mayank1513/persist-and-sync) — Zustand middleware to easily persist and sync Zustand state between tabs/windows/iframes with same origin.33- [shared-zustand](https://github.com/Tom-Julux/shared-zustand) — Cross-tab state sharing for Zustand.34- [simple-zustand-devtools](https://github.com/beerose/simple-zustand-devtools) — 🐻⚛️ Inspect your Zustand store in React DevTools.35- [solid-zustand](https://github.com/wobsoriano/solid-zustand) — State management in Solid using Zustand.36- [treeshakable](https://github.com/react18-tools/treeshakable) — A wrapper for library creators to avoid redundant store creation.37- [use-broadcast-ts](https://github.com/Romainlg29/use-broadcast) — Zustand middleware to share state between tabs.38- [use-post-message-ts](https://github.com/paulschoen/use-post-message) — Zustand middleware for sharing state between cross-origin iframes via postMessage browser method.39- [use-zustand](https://github.com/zustandjs/use-zustand) — Another custom hook to use Zustand vanilla store.40- [vue-zustand](https://github.com/wobsoriano/vue-zustand) — State management solution for Vue based on Zustand.41- [zoov](https://github.com/InfiniteXyy/zoov) — State management solution based on Zustand with Module-like API.42- [zubridge](https://github.com/goosewobbler/zubridge) — Use Zustand in cross-platform apps, seamlessly. Supports Electron & Tauri.43- [zukeeper](https://github.com/oslabs-beta/Zukeeper) — Native devtools with state and action tracking, diffing, tree display, and time travel44- [zundo](https://github.com/charkour/zundo) — 🍜 Undo and redo middleware for Zustand, enabling time-travel in your apps.45- [zustand-ards](https://github.com/ivoilic/zustand-ards) — 💁 Simple opinionated utilities for example alternative selector formats and default shallow hooks46- [zustand-async-slice](https://github.com/mym0404/zustand-async-slice) — Simple Zustand utility to create Async Slice. TypeScript Fully Supported 🖖47- [zustand-boilerplate](https://github.com/sagiereder/zustand-boilerplate) — A tool that automatically generates getters, setters and more for your zustand store.48- [zustand-computed](https://github.com/chrisvander/zustand-computed) — A Zustand middleware to create computed states.49- [zustand-computed-state](https://github.com/yasintz/zustand-computed-state) — Simple middleware to add computed states.50- [zustand-constate](https://github.com/ntvinhit/zustand-constate) — Context-based state management based on Zustand and taking ideas from Constate.51- [zustand-context](https://github.com/fredericoo/zustand-context) — Create a zustand store in React Context, containing an initial value, or use it in your components with isolated, mockable instances.52- [zustand-create-setter-fn](https://www.npmjs.com/package/zustand-create-setter-fn) — A fully type safe utility for Zustand that allows you to easily update state using React style `setState` functions (framework agnostic, doesn't require React).53- [zustand-di](https://github.com/charkour/zustand-di) — use react props to init zustand stores54- [zustand-forms](https://github.com/Conduct/zustand-forms) — Fast, type safe form states as Zustand stores.55- [zustand-hash-storage](https://github.com/MartinGamesCZ/zustand-hash-storage) — Zustand middleware for saving state into URL hash, b64 encoded (can be configured) and debounce timer.56- [zustand-injectors](https://github.com/zustandjs/zustand-injectors) — A sweet way to lazy load slices57- [zustand-interval-persist](https://www.npmjs.com/package/zustand-interval-persist) — An enhancement for zustand that enables automatic saving of the store's state to the specified storage at regular interval.58- [zustand-lit](https://github.com/ennjin/zustand-lit) — A zustand adapter for lit.js (LitElement)59- [zustand-middleware-computed-state](https://github.com/cmlarsen/zustand-middleware-computed-state) — A dead simple middleware for adding computed state to Zustand.60- [zustand-middleware-xstate](https://github.com/biowaffeln/zustand-middleware-xstate) — A middleware for putting XState state machines into a global Zustand store.61- [zustand-middleware-yjs](https://github.com/joebobmiles/zustand-middleware-yjs) — A middleware for synchronizing Zustand stores with Yjs.62- [zustand-mmkv-storage](https://github.com/1mehdifaraji/zustand-mmkv-storage) — Fast, lightweight MMKV storage adapter for Zustand persist middleware in React Native.63- [zustand-multi-persist](https://github.com/mooalot/zustand-multi-persist) — A middleware for persisting and rehydrating state to multiple storage engines.64- [zustand-mutable](https://github.com/zustandjs/zustand-mutable) — A sweet way to use immer-like mutable updates.65- [zustand-namespaces](https://github.com/mooalot/zustand-namespaces) — One store to rule them all. Namespaced Zustand stores.66- [zustand-persist](https://github.com/roadmanfong/zustand-persist) — A middleware for persisting and rehydrating state.67- [zustand-pub](https://github.com/AwesomeDevin/zustand-pub) — Cross-Application/Cross-Framework State Management And Sharing based on zustand and zustand-vue for React/Vue.68- [zustand-querystring](https://github.com/nitedani/zustand-querystring) — A Zustand middleware that syncs the store with the querystring.69- [zustand-rx](https://github.com/patdx/zustand-rx) — A Zustand middleware enabling you to subscribe to a store as an RxJS Observable.70- [zustand-saga](https://github.com/Nowsta/zustand-saga) — A Zustand middleware for redux-saga (minus redux).71- [zustand-slices](https://github.com/zustandjs/zustand-slices) — A slice utility for Zustand.72- [zustand-store-addons](https://github.com/Diablow/zustand-store-addons) — React state management addons for Zustand.73- [zustand-sync-tabs](https://github.com/mayank1513/zustand-sync-tabs) — Zustand middleware to easily sync Zustand state between tabs/windows/iframes with same origin.74- [zustand-utils](https://www.npmjs.com/package/zustand-utils) — Utilities for Zustand — a `createContext` replacement, a devtools wrapper, and a store-updater factory function.75- [zustand-valtio](https://github.com/zustandjs/zustand-valtio) — A sweet combination of Zustand and Valtio76- [zustand-vue](https://github.com/AwesomeDevin/zustand-vue) — State management for vue (Vue3 / Vue2) based on zustand.77- [zustand-x](https://github.com/udecode/zustand-x) — Zustand store factory for a best-in-class developer experience.78- [zustand-xs](https://github.com/zustandjs/zustand-xs) — XState/store compabile middleware for Zustand79- [zustand-yjs](https://github.com/tandem-pt/zustand-yjs) — Zustand stores for Yjs structures.80- [zusteller](https://github.com/timkindberg/zusteller) — Your global state savior. "Just hooks" + Zustand.81- [zustorm](https://github.com/mooalot/zustorm) — A simple and powerful form library for Zustand.82- [zusty](https://github.com/oslabs-beta/Zusty) — Zustand tool to assist debugging with time travel, action logs, state snapshots, store view, render time metrics and state component tree.
added:docs/reference/middlewares/combine.md+103 added
1---2title: combine3description: How to create a store and get types automatically inferred4nav: 325---67# combine89`combine` middleware lets you create a cohesive state by merging an initial state with a state10creator function that adds new state slices and actions. This is really helpful as it automatically11infers types, so there’s no need for explicit type definitions.1213> [!TIP]14> This makes state management more straightforward and efficient by making curried version of15> `create` and `createStore` not necessary for middleware usage.1617```js18const nextStateCreatorFn = combine(initialState, additionalStateCreatorFn)19```2021- [Types](#types)22 - [Signature](#combine-signature)23- [Reference](#reference)24- [Usage](#usage)25 - [Creating a state with inferred types](#creating-a-state-wit-inferred-types)26- [Troubleshooting](#troubleshooting)2728## Types2930### Signature3132```ts33combine<T, U>(initialState: T, additionalStateCreatorFn: StateCreator<T, [], [], U>): StateCreator<Omit<T, keyof U> & U, [], []>34```3536## Reference3738### `combine(initialState, additionalStateCreatorFn)`3940#### Parameters4142- `initialState`: The value you want the state to be initially. It can be a value of any type,43 except a function.44- `additionalStateCreatorFn`: A function that takes `set` function, `get` function and `store` as45 arguments. Usually, you will return an object with the methods you want to expose.4647#### Returns4849`combine` returns a state creator function.5051## Usage5253### Creating a store with inferred types5455This example shows you how you can create a store and get types automatically inferred, so you56don’t need to define them explicitly.5758```ts59import { createStore } from 'zustand/vanilla'60import { combine } from 'zustand/middleware'6162const positionStore = createStore(63 combine({ position: { x: 0, y: 0 } }, (set) => ({64 setPosition: (position) => set({ position }),65 })),66)6768const $dotContainer = document.getElementById('dot-container') as HTMLDivElement69const $dot = document.getElementById('dot') as HTMLDivElement7071$dotContainer.addEventListener('pointermove', (event) => {72 positionStore.getState().setPosition({73 x: event.clientX,74 y: event.clientY,75 })76})7778const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {79 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`80}8182render(positionStore.getInitialState(), positionStore.getInitialState())8384positionStore.subscribe(render)85```8687Here's the `html` code8889```html90<div91 id="dot-container"92 style="position: relative; width: 100vw; height: 100vh;"93>94 <div95 id="dot"96 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"97 ></div>98</div>99```100101## Troubleshooting102103TBD
added:docs/reference/middlewares/devtools.md+352 added
1---2title: devtools3description: How to time-travel debug your store4nav: 295---67# devtools89`devtools` middleware lets you use [Redux DevTools Extension](https://github.com/reduxjs/redux-devtools)10without Redux. Read more about the benefits of using [Redux DevTools for debugging](https://redux.js.org/style-guide/#use-the-redux-devtools-extension-for-debugging).1112> [!IMPORTANT]13> In order to use `devtools` from `zustand/middleware` you need to install14> `@redux-devtools/extension` library.1516```js17const nextStateCreatorFn = devtools(stateCreatorFn, devtoolsOptions)18```1920- [Types](#types)21 - [Signature](#signature)22 - [Mutator](#mutator)23- [Reference](#reference)24- [Usage](#usage)25 - [Debugging a store](#debugging-a-store)26 - [Debugging a Slices pattern based store](#debugging-a-slices-pattern-based-store)27 - [Filtering actions with actionsDenylist](#filtering-actions-with-actionsdenylist)28 - [Cleanup](#cleanup)29- [Troubleshooting](#troubleshooting)30 - [Only one store is displayed](#only-one-store-is-displayed)31 - [Action names are labeled as 'anonymous'](#all-action-names-are-labeled-as-anonymous)3233## Types3435### Signature3637```ts38devtools<T>(stateCreatorFn: StateCreator<T, [], []>, devtoolsOptions?: DevtoolsOptions): StateCreator<T, [['zustand/devtools', never]], []>39```4041### Mutator4243<!-- prettier-ignore-start -->44```ts45['zustand/devtools', never]46```47<!-- prettier-ignore-end -->4849## Reference5051### `devtools(stateCreatorFn, devtoolsOptions)`5253#### Parameters5455- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.56 Usually, you will return an object with the methods you want to expose.57- **optional** `devtoolsOptions`: An object to define `Redux Devtools` options.58 - **optional** `name`: A custom identifier for the connection in the Redux DevTools.59 - **optional** `enabled`: Defaults to `true` when is on development mode, and defaults to `false`60 when is on production mode. Enables or disables the Redux DevTools integration61 for this store.62 - **optional** `anonymousActionType`: Defaults to the inferred action type or `anonymous` if63 unavailable. A string to use as the action type for anonymous mutations in the Redux DevTools.64 - **optional** `store`: A custom identifier for the store in the Redux DevTools.65 - **optional** `actionsDenylist`: A string or array of strings (regex patterns) that specify which66 actions should be filtered out from Redux DevTools. This option is passed directly to Redux DevTools67 for filtering. For example, `['secret.*']` will filter out all actions starting with "secret".6869#### Returns7071`devtools` returns a state creator function.7273## Usage7475### Debugging a store7677This example shows you how you can use `Redux Devtools` to debug a store7879```ts80import { create, StateCreator } from 'zustand'81import { devtools } from 'zustand/middleware'8283type JungleStore = {84 bears: number85 addBear: () => void86 fishes: number87 addFish: () => void88}8990const useJungleStore = create<JungleStore>()(91 devtools((set) => ({92 bears: 0,93 addBear: () =>94 set((state) => ({ bears: state.bears + 1 }), undefined, 'jungle/addBear'),95 fishes: 0,96 addFish: () =>97 set(98 (state) => ({ fishes: state.fishes + 1 }),99 undefined,100 'jungle/addFish',101 ),102 })),103)104```105106### Debugging a Slices pattern based store107108This example shows you how you can use `Redux Devtools` to debug a Slices pattern based store109110```ts111import { create, StateCreator } from 'zustand'112import { devtools } from 'zustand/middleware'113114type BearSlice = {115 bears: number116 addBear: () => void117}118119type FishSlice = {120 fishes: number121 addFish: () => void122}123124type JungleStore = BearSlice & FishSlice125126const createBearSlice: StateCreator<127 JungleStore,128 [['zustand/devtools', never]],129 [],130 BearSlice131> = (set) => ({132 bears: 0,133 addBear: () =>134 set(135 (state) => ({ bears: state.bears + 1 }),136 undefined,137 'jungle:bear/addBear',138 ),139})140141const createFishSlice: StateCreator<142 JungleStore,143 [['zustand/devtools', never]],144 [],145 FishSlice146> = (set) => ({147 fishes: 0,148 addFish: () =>149 set(150 (state) => ({ fishes: state.fishes + 1 }),151 undefined,152 'jungle:fish/addFish',153 ),154})155156const useJungleStore = create<JungleStore>()(157 devtools((...args) => ({158 ...createBearSlice(...args),159 ...createFishSlice(...args),160 })),161)162```163164### Filtering actions with actionsDenylist165166You can filter out specific actions from Redux DevTools using the `actionsDenylist` option. This is useful for hiding internal or sensitive actions from the DevTools timeline.167168```ts169import { create } from 'zustand'170import { devtools } from 'zustand/middleware'171172type Store = {173 user: string | null174 token: string | null175 login: (user: string, token: string) => void176 logout: () => void177 updateData: () => void178}179180const useStore = create<Store>()(181 devtools(182 (set) => ({183 user: null,184 token: null,185 login: (user, token) => set({ user, token }, undefined, 'auth/login'),186 logout: () => set({ user: null, token: null }, undefined, 'auth/logout'),187 updateData: () =>188 set({ user: 'updated' }, undefined, 'internal/updateData'),189 }),190 {191 name: 'AuthStore',192 // Filter out actions matching these regex patterns193 actionsDenylist: ['internal/.*'], // Hides all 'internal/*' actions194 },195 ),196)197```198199You can also use a single regex string:200201```ts202const useStore = create<Store>()(203 devtools(204 (set) => ({205 // ... state and actions206 }),207 {208 name: 'MyStore',209 actionsDenylist: 'secret.*', // Hides all actions starting with 'secret'210 },211 ),212)213```214215> [!NOTE]216> The `actionsDenylist` option uses regex pattern matching and is handled directly by Redux DevTools Extension.217> All actions are still sent to DevTools, but matching actions are filtered from the display.218219### Cleanup220221When a store is no longer needed, you can clean up the Redux DevTools connection by calling the `cleanup` method on the store:222223```ts224import { create } from 'zustand'225import { devtools } from 'zustand/middleware'226227const useStore = create(228 devtools((set) => ({229 count: 0,230 increment: () => set((state) => ({ count: state.count + 1 })),231 })),232)233234// When you're done with the store, clean it up235useStore.devtools.cleanup()236```237238This is particularly useful in applications that wrap store in context or create multiple stores dynamically.239240## Troubleshooting241242### Only one store is displayed243244By default, `Redux Devtools` only show one store at a time, so in order to see other stores you245need to use store selector and choose a different store.246247### All action names are labeled as 'anonymous'248249If an action type name is not provided, it is defaulted to "anonymous". You can customize this250default value by providing a `anonymousActionType` parameter:251252For instance the next example doesn't have action type name:253254```ts255import { create, StateCreator } from 'zustand'256import { devtools } from 'zustand/middleware'257258type BearSlice = {259 bears: number260 addBear: () => void261}262263type FishSlice = {264 fishes: number265 addFish: () => void266}267268type JungleStore = BearSlice & FishSlice269270const createBearSlice: StateCreator<271 JungleStore,272 [['zustand/devtools', never]],273 [],274 BearSlice275> = (set) => ({276 bears: 0,277 addBear: () => set((state) => ({ bears: state.bears + 1 })),278 eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),279})280281const createFishSlice: StateCreator<282 JungleStore,283 [['zustand/devtools', never]],284 [],285 FishSlice286> = (set) => ({287 fishes: 0,288 addFish: () => set((state) => ({ fishes: state.fishes + 1 })),289})290291const useJungleStore = create<JungleStore>()(292 devtools((...args) => ({293 ...createBearSlice(...args),294 ...createFishSlice(...args),295 })),296)297```298299In order to fix the previous example, we need to provide an action type name as the third parameter.300Additionally, to preserve the default behavior of the replacement logic, the second parameter301should be set to `undefined`.302303Here's the fixed previous example304305```ts306import { create, StateCreator } from 'zustand'307308type BearSlice = {309 bears: number310 addBear: () => void311}312313type FishSlice = {314 fishes: number315 addFish: () => void316}317318type JungleStore = BearSlice & FishSlice319320const createBearSlice: StateCreator<321 JungleStore,322 [['zustand/devtools', never]],323 [],324 BearSlice325> = (set) => ({326 bears: 0,327 addBear: () =>328 set((state) => ({ bears: state.bears + 1 }), undefined, 'bear/addBear'),329})330331const createFishSlice: StateCreator<332 JungleStore,333 [['zustand/devtools', never]],334 [],335 FishSlice336> = (set) => ({337 fishes: 0,338 addFish: () =>339 set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fish/addFish'),340})341342const useJungleStore = create<JungleStore>()(343 devtools((...args) => ({344 ...createBearSlice(...args),345 ...createFishSlice(...args),346 })),347)348```349350> [!IMPORTANT]351> Do not set the second parameter to `true` or `false` unless you want to override the default352> replacement logic
added:docs/reference/middlewares/immer.md+239 added
1---2title: immer3description: How to perform immutable updates in a store without boilerplate code4nav: 315---67# immer89`immer` middleware lets you perform immutable updates.1011> [!IMPORTANT]12> In order to use `immer` from `zustand/middleware/immer` you need to install13> `immer` library.1415```js16const nextStateCreatorFn = immer(stateCreatorFn)17```1819- [Types](#types)20 - [Signature](#signature)21 - [Mutator](#mutator)22- [Reference](#reference)23- [Usage](#usage)24- [Troubleshooting](#troubleshooting)2526## Types2728### Signature2930```ts31immer<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/immer', never]], []>32```3334### Mutator3536<!-- prettier-ignore-start -->37```ts38['zustand/immer', never]39```40<!-- prettier-ignore-end -->4142## Reference4344### `immer(stateCreatorFn)`4546#### Parameters4748- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.49 Usually, you will return an object with the methods you want to expose.5051#### Returns5253`immer` returns a state creator function.5455## Usage5657### Updating state without boilerplate code5859In the next example, we're going to update the `person` object. Since it's a nested object, we need60to create a copy of the entire object before making the update.6162```ts63import { createStore } from 'zustand/vanilla'6465type PersonStoreState = {66 person: { firstName: string; lastName: string; email: string }67}6869type PersonStoreActions = {70 setPerson: (71 nextPerson: (72 person: PersonStoreState['person'],73 ) => PersonStoreState['person'] | PersonStoreState['person'],74 ) => void75}7677type PersonStore = PersonStoreState & PersonStoreActions7879const personStore = createStore<PersonStore>()((set) => ({80 person: {81 firstName: 'Barbara',82 lastName: 'Hepworth',83 email: 'bhepworth@sculpture.com',84 },85 setPerson: (nextPerson) =>86 set((state) => ({87 person:88 typeof nextPerson === 'function'89 ? nextPerson(state.person)90 : nextPerson,91 })),92}))9394const $firstNameInput = document.getElementById(95 'first-name',96) as HTMLInputElement97const $lastNameInput = document.getElementById('last-name') as HTMLInputElement98const $emailInput = document.getElementById('email') as HTMLInputElement99const $result = document.getElementById('result') as HTMLDivElement100101function handleFirstNameChange(event: Event) {102 personStore.getState().setPerson((person) => ({103 ...person,104 firstName: (event.target as any).value,105 }))106}107108function handleLastNameChange(event: Event) {109 personStore.getState().setPerson((person) => ({110 ...person,111 lastName: (event.target as any).value,112 }))113}114115function handleEmailChange(event: Event) {116 personStore.getState().setPerson((person) => ({117 ...person,118 email: (event.target as any).value,119 }))120}121122$firstNameInput.addEventListener('input', handleFirstNameChange)123$lastNameInput.addEventListener('input', handleLastNameChange)124$emailInput.addEventListener('input', handleEmailChange)125126const render: Parameters<typeof personStore.subscribe>[0] = (state) => {127 $firstNameInput.value = state.person.firstName128 $lastNameInput.value = state.person.lastName129 $emailInput.value = state.person.email130131 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`132}133134render(personStore.getInitialState(), personStore.getInitialState())135136personStore.subscribe(render)137```138139Here's the `html` code140141```html142<label style="display: block">143 First name:144 <input id="first-name" />145</label>146<label style="display: block">147 Last name:148 <input id="last-name" />149</label>150<label style="display: block">151 Email:152 <input id="email" />153</label>154<p id="result"></p>155```156157To avoid manually copying the entire object before making updates, we'll use the `immer`158middleware.159160```ts161import { createStore } from 'zustand/vanilla'162import { immer } from 'zustand/middleware/immer'163164type PersonStoreState = {165 person: { firstName: string; lastName: string; email: string }166}167168type PersonStoreActions = {169 setPerson: (170 nextPerson: (171 person: PersonStoreState['person'],172 ) => PersonStoreState['person'] | PersonStoreState['person'],173 ) => void174}175176type PersonStore = PersonStoreState & PersonStoreActions177178const personStore = createStore<PersonStore>()(179 immer((set) => ({180 person: {181 firstName: 'Barbara',182 lastName: 'Hepworth',183 email: 'bhepworth@sculpture.com',184 },185 setPerson: (nextPerson) =>186 set((state) => {187 state.person =188 typeof nextPerson === 'function'189 ? nextPerson(state.person)190 : nextPerson191 }),192 })),193)194195const $firstNameInput = document.getElementById(196 'first-name',197) as HTMLInputElement198const $lastNameInput = document.getElementById('last-name') as HTMLInputElement199const $emailInput = document.getElementById('email') as HTMLInputElement200const $result = document.getElementById('result') as HTMLDivElement201202function handleFirstNameChange(event: Event) {203 personStore.getState().setPerson((person) => {204 person.firstName = (event.target as any).value205 })206}207208function handleLastNameChange(event: Event) {209 personStore.getState().setPerson((person) => {210 person.lastName = (event.target as any).value211 })212}213214function handleEmailChange(event: Event) {215 personStore.getState().setPerson((person) => {216 person.email = (event.target as any).value217 })218}219220$firstNameInput.addEventListener('input', handleFirstNameChange)221$lastNameInput.addEventListener('input', handleLastNameChange)222$emailInput.addEventListener('input', handleEmailChange)223224const render: Parameters<typeof personStore.subscribe>[0] = (state) => {225 $firstNameInput.value = state.person.firstName226 $lastNameInput.value = state.person.lastName227 $emailInput.value = state.person.email228229 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`230}231232render(personStore.getInitialState(), personStore.getInitialState())233234personStore.subscribe(render)235```236237## Troubleshooting238239TBD
added:docs/reference/middlewares/persist.md+988 added
1---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```ts34persist<T, U>(stateCreatorFn: StateCreator<T, [], []>, persistOptions?: PersistOptions<T, U>): StateCreator<T, [['zustand/persist', U]], []>35```3637### Mutator3839<!-- prettier-ignore-start -->40```ts41['zustand/persist', U]42```43<!-- prettier-ignore-end -->4445## Reference4647### `persist(stateCreatorFn)`4849#### Parameters5051- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.52 Usually, you will return an object with the methods you want to expose.53- `persistOptions`: An object to define storage options.54 - `name`: A unique name of the item for your store in the storage.55 - **optional** `storage`: Defaults to `createJSONStorage(() => localStorage)`.56 - **optional** `partialize`: A function to filter state fields before persisting it.57 - **optional** `onRehydrateStorage`: A function or function returning a function that allows58 custom logic before and after state rehydration.59 - **optional** `version`: A version number for the persisted state. If the stored state version60 doesn't match, it won't be used.61 - **optional** `migrate`: A function to migrate persisted state if the version mismatch occurs.62 - **optional** `merge`: A function for custom logic when merging persisted state with the current63 state during rehydration. Defaults to a shallow merge.64 - **optional** `skipHydration`: Defaults to `false`. If `true`, the middleware won't65 automatically rehydrate the state on initialization. Use `rehydrate` function manually in this66 case. This is useful for server-side rendering (SSR) applications.6768#### Returns6970`persist` returns a state creator function.7172## Usage7374### Persisting a state7576In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`77middleware. The example tracks the `position` of the mouse as it moves within a container and78stores the `position` in local storage, so it persists even when the page reloads.7980We start by setting up a vanilla store that holds the position (an object with `x` and `y`81coordinates) and an action to update it. We'll also use the `persist` middleware to store the82position in `localStorage`.8384```ts85import { createStore } from 'zustand/vanilla'86import { persist } from 'zustand/middleware'8788type PositionStoreState = { position: { x: number; y: number } }8990type PositionStoreActions = {91 setPosition: (nextPosition: PositionStoreState['position']) => void92}9394type PositionStore = PositionStoreState & PositionStoreActions9596const positionStore = createStore<PositionStore>()(97 persist(98 (set) => ({99 position: { x: 0, y: 0 },100 setPosition: (position) => set({ position }),101 }),102 { name: 'position-storage' },103 ),104)105```106107Next, we'll track the mouse movements inside a div and update the store with the new position.108109```ts110const $dotContainer = document.getElementById('dot-container') as HTMLDivElement111const $dot = document.getElementById('dot') as HTMLDivElement112113$dotContainer.addEventListener('pointermove', (event) => {114 positionStore.getState().setPosition({115 x: event.clientX,116 y: event.clientY,117 })118})119```120121We want to reflect the position updates on the screen by moving a div element122(representing the dot) to the new coordinates.123124```ts125const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {126 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`127}128129render(positionStore.getState(), positionStore.getState())130131positionStore.subscribe(render)132```133134Here’s the complete code.135136```ts137import { createStore } from 'zustand/vanilla'138import { persist } from 'zustand/middleware'139140type PositionStoreState = { position: { x: number; y: number } }141142type PositionStoreActions = {143 setPosition: (nextPosition: PositionStoreState['position']) => void144}145146type PositionStore = PositionStoreState & PositionStoreActions147148const positionStore = createStore<PositionStore>()(149 persist(150 (set) => ({151 position: { x: 0, y: 0 },152 setPosition: (position) => set({ position }),153 }),154 { name: 'position-storage' },155 ),156)157158const $dotContainer = document.getElementById('dot-container') as HTMLDivElement159const $dot = document.getElementById('dot') as HTMLDivElement160161$dotContainer.addEventListener('pointermove', (event) => {162 positionStore.getState().setPosition({163 x: event.clientX,164 y: event.clientY,165 })166})167168const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {169 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`170}171172render(positionStore.getState(), positionStore.getState())173174positionStore.subscribe(render)175```176177Here's the `html` code178179```html180<div181 id="dot-container"182 style="position: relative; width: 100vw; height: 100vh;"183>184 <div185 id="dot"186 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"187 ></div>188</div>189```190191### Persisting a state partially192193In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`194middleware. Additionally, we'll show you how to persist only part of the state195(partial persistence), which can be useful when you don’t want to store the entire state in196`localStorage`.197198We’ll first create a vanilla store that holds the position state and actions to update it. We'll199use the `persist` middleware to persist only the relevant part of the state (in this case, the200context containing the position).201202```ts203import { createStore } from 'zustand/vanilla'204import { persist } from 'zustand/middleware'205206type PositionStoreState = {207 context: {208 position: { x: number; y: number }209 }210}211212type PositionStoreActions = {213 actions: {214 setPosition: (215 nextPosition: PositionStoreState['context']['position'],216 ) => void217 }218}219220type PositionStore = PositionStoreState & PositionStoreActions221222const positionStore = createStore<PositionStore>()(223 persist(224 (set) => ({225 context: {226 position: { x: 0, y: 0 },227 },228 actions: {229 setPosition: (position) => set({ context: { position } }),230 },231 }),232 {233 name: 'position-storage',234 partialize: (state) => ({ context: state.context }),235 },236 ),237)238```239240Next, we'll track the mouse movements inside a div and update the store with the new position.241242```ts243const $dotContainer = document.getElementById('dot-container') as HTMLDivElement244const $dot = document.getElementById('dot') as HTMLDivElement245246$dotContainer.addEventListener('pointermove', (event) => {247 positionStore.getState().actions.setPosition({248 x: event.clientX,249 y: event.clientY,250 })251})252```253254We want to reflect the position updates on the screen by moving a div element255(representing the dot) to the new coordinates.256257```ts258const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {259 $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`260}261262render(positionStore.getState(), positionStore.getState())263264positionStore.subscribe(render)265```266267Here’s the full code to create a dot that follows your mouse movement inside a container and268persists the `context` in `localStorage`.269270```ts271import { createStore } from 'zustand/vanilla'272import { persist } from 'zustand/middleware'273274type PositionStoreState = {275 context: {276 position: { x: number; y: number }277 }278}279280type PositionStoreActions = {281 actions: {282 setPosition: (283 nextPosition: PositionStoreState['context']['position'],284 ) => void285 }286}287288type PositionStore = PositionStoreState & PositionStoreActions289290const positionStore = createStore<PositionStore>()(291 persist(292 (set) => ({293 context: {294 position: { x: 0, y: 0 },295 },296 actions: {297 setPosition: (position) => set({ context: { position } }),298 },299 }),300 {301 name: 'position-storage',302 partialize: (state) => ({ context: state.context }),303 },304 ),305)306307const $dotContainer = document.getElementById('dot-container') as HTMLDivElement308const $dot = document.getElementById('dot') as HTMLDivElement309310$dotContainer.addEventListener('pointermove', (event) => {311 positionStore.getState().actions.setPosition({312 x: event.clientX,313 y: event.clientY,314 })315})316317const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {318 $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`319}320321render(positionStore.getState(), positionStore.getState())322323positionStore.subscribe(render)324```325326Here's the `html` code327328```html329<div330 id="dot-container"331 style="position: relative; width: 100vw; height: 100vh;"332>333 <div334 id="dot"335 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"336 ></div>337</div>338```339340### Persisting a state with custom storage341342In this mini tutorial, we’ll create a simple position-tracking system using vanilla store, where343the position state is persisted in the URL's search parameters. This approach allows state344persistence directly in the browser's URL, which can be useful for maintaining state across page345reloads or sharing links with state embedded.346347We need to implement functions to manipulate URL search parameters as if they were a storage348mechanism. This includes retrieving, setting, and removing parameters.349350```ts351const getSearchParams = () => {352 return new URL(location.href).searchParams353}354355const updateSearchParams = (searchParams: URLSearchParams) => {356 window.history.replaceState(357 {},358 '',359 `${location.pathname}?${searchParams.toString()}`,360 )361}362363const getSearchParam = (key: string) => {364 const searchParams = getSearchParams()365 return searchParams.get(key)366}367368const updateSearchParam = (key: string, value: string) => {369 const searchParams = getSearchParams()370 searchParams.set(key, value)371372 updateSearchParams(searchParams)373}374375const removeSearchParam = (key: string) => {376 const searchParams = getSearchParams()377 searchParams.delete(key)378379 updateSearchParams(searchParams)380}381```382383To use the URL search parameters as storage, we define a `searchParamsStorage` object with384`getItem`, `setItem`, and `removeItem` methods. These methods map to our custom functions that385manipulate search parameters.386387```ts388const searchParamsStorage = {389 getItem: (key: string) => getSearchParam(key),390 setItem: (key: string, value: string) => updateSearchParam(key, value),391 removeItem: (key: string) => removeSearchParam(key),392}393```394395Now, we initialize the vanilla store using the `persist` middleware, specifying that we want to use396our custom storage. Instead of the default `localStorage` or `sessionStorage`, we’ll persist the397position data in the URL search parameters.398399```ts400import { createStore } from 'zustand/vanilla'401import { persist, createJSONStorage } from 'zustand/middleware'402403type PositionStoreState = { position: { x: number; y: number } }404405type PositionStoreActions = {406 setPosition: (nextPosition: PositionStoreState['position']) => void407}408409type PositionStore = PositionStoreState & PositionStoreActions410411const positionStore = createStore<PositionStore>()(412 persist(413 (set) => ({414 position: { x: 0, y: 0 },415 setPosition: (position) => set({ position }),416 }),417 {418 name: 'position-storage',419 storage: createJSONStorage(() => searchParamsStorage),420 },421 ),422)423```424425Next, we'll track the mouse movements inside a div and update the store with the new position.426427```ts428const $dotContainer = document.getElementById('dot-container') as HTMLDivElement429const $dot = document.getElementById('dot') as HTMLDivElement430431$dotContainer.addEventListener('pointermove', (event) => {432 positionStore.getState().setPosition({433 x: event.clientX,434 y: event.clientY,435 })436})437```438439We want to reflect the position updates on the screen by moving a div element440(representing the dot) to the new coordinates.441442```ts443const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {444 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`445}446447render(positionStore.getState(), positionStore.getState())448449positionStore.subscribe(render)450```451452Here’s the full code to create a dot that follows your mouse movement inside a container and453persists the position in URL's search parameters.454455```ts456import { createStore } from 'zustand/vanilla'457import { persist, createJSONStorage } from 'zustand/middleware'458459type PositionStoreState = { position: { x: number; y: number } }460461type PositionStoreActions = {462 setPosition: (nextPosition: PositionStoreState['position']) => void463}464465type PositionStore = PositionStoreState & PositionStoreActions466467const getSearchParams = () => {468 return new URL(location.href).searchParams469}470471const updateSearchParams = (searchParams: URLSearchParams) => {472 window.history.replaceState(473 {},474 '',475 `${location.pathname}?${searchParams.toString()}`,476 )477}478479const getSearchParam = (key: string) => {480 const searchParams = getSearchParams()481 return searchParams.get(key)482}483484const updateSearchParam = (key: string, value: string) => {485 const searchParams = getSearchParams()486 searchParams.set(key, value)487488 updateSearchParams(searchParams)489}490491const removeSearchParam = (key: string) => {492 const searchParams = getSearchParams()493 searchParams.delete(key)494495 updateSearchParams(searchParams)496}497498const searchParamsStorage = {499 getItem: (key: string) => getSearchParam(key),500 setItem: (key: string, value: string) => updateSearchParam(key, value),501 removeItem: (key: string) => removeSearchParam(key),502}503504const positionStore = createStore<PositionStore>()(505 persist(506 (set) => ({507 position: { x: 0, y: 0 },508 setPosition: (position) => set({ position }),509 }),510 {511 name: 'position-storage',512 storage: createJSONStorage(() => searchParamsStorage),513 },514 ),515)516517const $dotContainer = document.getElementById('dot-container') as HTMLDivElement518const $dot = document.getElementById('dot') as HTMLDivElement519520$dotContainer.addEventListener('pointermove', (event) => {521 positionStore.getState().setPosition({522 x: event.clientX,523 y: event.clientY,524 })525})526527const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {528 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`529}530531render(positionStore.getState(), positionStore.getState())532533positionStore.subscribe(render)534```535536Here's the `html` code537538```html539<div540 id="dot-container"541 style="position: relative; width: 100vw; height: 100vh;"542>543 <div544 id="dot"545 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"546 ></div>547</div>548```549550### Persisting a state through versioning and migrations551552In this tutorial, we’ll explore how to manage state persistence using versioning and migration.553We will demonstrate how to evolve your state schema across versions without breaking existing554persisted data.555556Before moving to versioned state management, we simulate an initial state for `version` 0. This is557done by manually setting a `version` 0 state in `localStorage` if it doesn't already exist. The558`version` 0 state saves the coordinates as `x` and `y` fields.559560```ts561// For tutorial purposes only562if (!localStorage.getItem('position-storage')) {563 localStorage.setItem(564 'position-storage',565 JSON.stringify({566 state: { x: 100, y: 100 }, // version 0 structure567 version: 0,568 }),569 )570}571```572573Next, we use `persist` middleware to handle state persistence. We also add a migration function to574handle changes between versions. In this example, we `migrate` the state from `version` 0 (where575`x` and `y` are separate) to `version` 1, where they are combined into a `position` object.576577```ts578migrate: (persisted: any, version) => {579 if (version === 0) {580 persisted.position = { x: persisted.x, y: persisted.y }581 delete persisted.x582 delete persisted.y583 }584585 return persisted586}587```588589Next, we'll track the mouse movements inside a div and update the store with the new position.590591```ts592const $dotContainer = document.getElementById('dot-container') as HTMLDivElement593const $dot = document.getElementById('dot') as HTMLDivElement594595$dotContainer.addEventListener('pointermove', (event) => {596 positionStore.getState().setPosition({597 x: event.clientX,598 y: event.clientY,599 })600})601```602603We want to reflect the position updates on the screen by moving a div element604(representing the dot) to the new coordinates.605606```ts607const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {608 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`609}610611render(positionStore.getState(), positionStore.getState())612613positionStore.subscribe(render)614```615616Here’s the complete code.617618```ts619import { createStore } from 'zustand/vanilla'620import { persist } from 'zustand/middleware'621622// For tutorial purposes only623if (!localStorage.getItem('position-storage')) {624 localStorage.setItem(625 'position-storage',626 JSON.stringify({627 state: { x: 100, y: 100 },628 version: 0,629 }),630 )631}632633type PositionStoreState = { position: { x: number; y: number } }634635type PositionStoreActions = {636 setPosition: (nextPosition: PositionStoreState['position']) => void637}638639type PositionStore = PositionStoreState & PositionStoreActions640641const positionStore = createStore<PositionStore>()(642 persist(643 (set) => ({644 position: { x: 0, y: 0 }, // version 0: just x: 0, y: 0645 setPosition: (position) => set({ position }),646 }),647 {648 name: 'position-storage',649 version: 1,650 migrate: (persisted: any, version) => {651 if (version === 0) {652 persisted.position = { x: persisted.x, y: persisted.y }653 delete persisted.x654 delete persisted.y655 }656657 return persisted658 },659 },660 ),661)662663const $dotContainer = document.getElementById('dot-container') as HTMLDivElement664const $dot = document.getElementById('dot') as HTMLDivElement665666$dotContainer.addEventListener('pointermove', (event) => {667 positionStore.getState().setPosition({668 x: event.clientX,669 y: event.clientY,670 })671})672673const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {674 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`675}676677render(positionStore.getState(), positionStore.getState())678679positionStore.subscribe(render)680```681682Here's the `html` code683684```html685<div686 id="dot-container"687 style="position: relative; width: 100vw; height: 100vh;"688>689 <div690 id="dot"691 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"692 ></div>693</div>694```695696### Persisting a state with nested objects697698In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`699and `y` coordinates. We will also implement persistence using `localStorage` and demonstrate how to700handle merging of state with potentially missing fields.701702To simulate an initial state for the tutorial, we will check if our position data exists in703`localStorage`. If it doesn't, we’ll set it up.704705```ts706if (!localStorage.getItem('position-storage')) {707 localStorage.setItem(708 'position-storage',709 JSON.stringify({710 state: { position: { y: 100 } }, // missing `x` field711 version: 0,712 }),713 )714}715```716717Now, we will create the store and configure it to use persistence and deep merging.718719```ts720import { createStore } from 'zustand/vanilla'721import { persist } from 'zustand/middleware'722import createDeepMerge from '@fastify/deepmerge'723724const deepMerge = createDeepMerge({ all: true })725726type PositionStoreState = { position: { x: number; y: number } }727728type PositionStoreActions = {729 setPosition: (nextPosition: PositionStoreState['position']) => void730}731732type PositionStore = PositionStoreState & PositionStoreActions733734const positionStore = createStore<PositionStore>()(735 persist(736 (set) => ({737 position: { x: 0, y: 0 },738 setPosition: (position) => set({ position }),739 }),740 {741 name: 'position-storage',742 merge: (persisted, current) => deepMerge(current, persisted) as never,743 },744 ),745)746```747748Next, we'll track the mouse movements inside a div and update the store with the new position.749750```ts751const $dotContainer = document.getElementById('dot-container') as HTMLDivElement752const $dot = document.getElementById('dot') as HTMLDivElement753754$dotContainer.addEventListener('pointermove', (event) => {755 positionStore.getState().setPosition({756 x: event.clientX,757 y: event.clientY,758 })759})760```761762We want to reflect the position updates on the screen by moving a div element763(representing the dot) to the new coordinates.764765```ts766const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {767 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`768}769770render(positionStore.getState(), positionStore.getState())771772positionStore.subscribe(render)773```774775Here’s the complete code.776777```ts778import { createStore } from 'zustand/vanilla'779import { persist } from 'zustand/middleware'780import createDeepMerge from '@fastify/deepmerge'781782const deepMerge = createDeepMerge({ all: true })783784// For tutorial purposes only785if (!localStorage.getItem('position-storage')) {786 localStorage.setItem(787 'position-storage',788 JSON.stringify({789 state: { position: { y: 100 } }, // missing `x` field790 version: 0,791 }),792 )793}794795type PositionStoreState = { position: { x: number; y: number } }796797type PositionStoreActions = {798 setPosition: (nextPosition: PositionStoreState['position']) => void799}800801type PositionStore = PositionStoreState & PositionStoreActions802803const positionStore = createStore<PositionStore>()(804 persist(805 (set) => ({806 position: { x: 0, y: 0 },807 setPosition: (position) => set({ position }),808 }),809 {810 name: 'position-storage',811 merge: (persisted, current) => deepMerge(current, persisted) as never,812 },813 ),814)815816const $dotContainer = document.getElementById('dot-container') as HTMLDivElement817const $dot = document.getElementById('dot') as HTMLDivElement818819$dotContainer.addEventListener('pointermove', (event) => {820 positionStore.getState().setPosition({821 x: event.clientX,822 y: event.clientY,823 })824})825826const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {827 console.log({ state })828 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`829}830831render(positionStore.getState(), positionStore.getState())832833positionStore.subscribe(render)834```835836Here's the `html` code837838```html839<div840 id="dot-container"841 style="position: relative; width: 100vw; height: 100vh;"842>843 <div844 id="dot"845 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"846 ></div>847</div>848```849850### Persisting a state and hydrate it manually851852In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`853and `y` coordinates. We will also implement persistence using `localStorage` and explore how to854skip the hydration process and manually trigger rehydration after a delay.855856We start by setting up a vanilla store that holds the position (an object with `x` and `y`857coordinates) and an action to update it. Furthermore, we'll also use the `persist` middleware to858store the position in `localStorage` but skipping hydration.859860```ts861import { createStore } from 'zustand/vanilla'862import { persist } from 'zustand/middleware'863864type PositionStoreState = { position: { x: number; y: number } }865866type PositionStoreActions = {867 setPosition: (nextPosition: PositionStoreState['position']) => void868}869870type PositionStore = PositionStoreState & PositionStoreActions871872const positionStore = createStore<PositionStore>()(873 persist(874 (set) => ({875 position: { x: 0, y: 0 },876 setPosition: (position) => set({ position }),877 }),878 {879 name: 'position-storage',880 skipHydration: true,881 },882 ),883)884```885886Since we skipped hydration in the initial setup, we will manually rehydrate the state. Here, we’re887using `setTimeout` to simulate a delayed rehydration.888889```ts890setTimeout(() => {891 positionStore.persist.rehydrate()892}, 2000)893```894895Next, we'll track the mouse movements inside a div and update the store with the new position.896897```ts898const $dotContainer = document.getElementById('dot-container') as HTMLDivElement899const $dot = document.getElementById('dot') as HTMLDivElement900901$dotContainer.addEventListener('pointermove', (event) => {902 positionStore.getState().setPosition({903 x: event.clientX,904 y: event.clientY,905 })906})907```908909We want to reflect the position updates on the screen by moving a div element910(representing the dot) to the new coordinates.911912```ts913const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {914 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`915}916917render(positionStore.getState(), positionStore.getState())918919positionStore.subscribe(render)920```921922Here’s the complete code.923924```ts925import { createStore } from 'zustand/vanilla'926import { persist } from 'zustand/middleware'927928type PositionStoreState = { position: { x: number; y: number } }929930type PositionStoreActions = {931 setPosition: (nextPosition: PositionStoreState['position']) => void932}933934type PositionStore = PositionStoreState & PositionStoreActions935936const positionStore = createStore<PositionStore>()(937 persist(938 (set) => ({939 position: { x: 0, y: 0 },940 setPosition: (position) => set({ position }),941 }),942 {943 name: 'position-storage',944 skipHydration: true,945 },946 ),947)948949const $dotContainer = document.getElementById('dot-container') as HTMLDivElement950const $dot = document.getElementById('dot') as HTMLDivElement951952$dotContainer.addEventListener('pointermove', (event) => {953 positionStore.getState().setPosition({954 x: event.clientX,955 y: event.clientY,956 })957})958959const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {960 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`961}962963setTimeout(() => {964 positionStore.persist.rehydrate()965}, 2000)966967render(positionStore.getState(), positionStore.getState())968969positionStore.subscribe(render)970```971972Here's the `html` code973974```html975<div976 id="dot-container"977 style="position: relative; width: 100vw; height: 100vh;"978>979 <div980 id="dot"981 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"982 ></div>983</div>984```985986## Troubleshooting987988TBD
added:docs/reference/middlewares/redux.md+172 added
1---2title: redux3description: How to use actions and reducers in a store4nav: 305---67# redux89`redux` middleware lets you update a store through actions and reducers just like redux.1011```js12const nextStateCreatorFn = redux(reducerFn, initialState)13```1415- [Types](#types)16 - [Signature](#signature)17 - [Mutator](#mutator)18- [Reference](#reference)19- [Usage](#usage)20 - [Updating state through actions and reducers](#updating-state-through-actions-and-reducers)21- [Troubleshooting](#troubleshooting)2223## Types2425### Signature2627```ts28redux<T, A>(reducerFn: (state: T, action: A) => T, initialState: T): StateCreator<T & { dispatch: (action: A) => A }, [['zustand/redux', A]], []>29```3031### Mutator3233<!-- prettier-ignore-start -->34```ts35['zustand/redux', A]36```37<!-- prettier-ignore-end -->3839## Reference4041### `redux(reducerFn, initialState)`4243#### Parameters4445- `reducerFn`: It should be pure and should take the current state of your application and an action46 object as arguments, and returns the new state resulting from applying the action.47- `initialState`: The value you want the state to be initially. It can be a value of any type,48 except a function.4950#### Returns5152`redux` returns a state creator function.5354## Usage5556### Updating state through actions and reducers5758```ts59import { createStore } from 'zustand/vanilla'60import { redux } from 'zustand/middleware'6162type PersonStoreState = {63 firstName: string64 lastName: string65 email: string66}6768type PersonStoreAction =69 | { type: 'person/setFirstName'; firstName: string }70 | { type: 'person/setLastName'; lastName: string }71 | { type: 'person/setEmail'; email: string }7273type PersonStore = PersonStoreState & {74 dispatch: (action: PersonStoreAction) => PersonStoreAction75}7677const personStoreReducer = (78 state: PersonStoreState,79 action: PersonStoreAction,80) => {81 switch (action.type) {82 case 'person/setFirstName': {83 return { ...state, firstName: action.firstName }84 }85 case 'person/setLastName': {86 return { ...state, lastName: action.lastName }87 }88 case 'person/setEmail': {89 return { ...state, email: action.email }90 }91 default: {92 return state93 }94 }95}9697const personStoreInitialState: PersonStoreState = {98 firstName: 'Barbara',99 lastName: 'Hepworth',100 email: 'bhepworth@sculpture.com',101}102103const personStore = createStore<PersonStore>()(104 redux(personStoreReducer, personStoreInitialState),105)106107const $firstNameInput = document.getElementById(108 'first-name',109) as HTMLInputElement110const $lastNameInput = document.getElementById('last-name') as HTMLInputElement111const $emailInput = document.getElementById('email') as HTMLInputElement112const $result = document.getElementById('result') as HTMLDivElement113114function handleFirstNameChange(event: Event) {115 personStore.dispatch({116 type: 'person/setFirstName',117 firstName: (event.target as any).value,118 })119}120121function handleLastNameChange(event: Event) {122 personStore.dispatch({123 type: 'person/setLastName',124 lastName: (event.target as any).value,125 })126}127128function handleEmailChange(event: Event) {129 personStore.dispatch({130 type: 'person/setEmail',131 email: (event.target as any).value,132 })133}134135$firstNameInput.addEventListener('input', handleFirstNameChange)136$lastNameInput.addEventListener('input', handleLastNameChange)137$emailInput.addEventListener('input', handleEmailChange)138139const render: Parameters<typeof personStore.subscribe>[0] = (person) => {140 $firstNameInput.value = person.firstName141 $lastNameInput.value = person.lastName142 $emailInput.value = person.email143144 $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`145}146147render(personStore.getInitialState(), personStore.getInitialState())148149personStore.subscribe(render)150```151152Here's the `html` code153154```html155<label style="display: block">156 First name:157 <input id="first-name" />158</label>159<label style="display: block">160 Last name:161 <input id="last-name" />162</label>163<label style="display: block">164 Email:165 <input id="email" />166</label>167<p id="result"></p>168```169170## Troubleshooting171172TBD
added:docs/reference/middlewares/subscribe-with-selector.md+121 added
1---2title: subscribeWithSelector3description: How to subscribe to granular store updates in a store4nav: 335---67# subscribeWithSelector89`subscribeWithSelector` middleware lets you subscribe to specific data based on current state.1011```js12const nextStateCreatorFn = subscribeWithSelector(stateCreatorFn)13```1415- [Types](#types)16 - [Signature](#signature)17 - [Mutator](#mutator)18- [Reference](#reference)19- [Usage](#usage)20- [Troubleshooting](#troubleshooting)2122## Types2324### Signature2526```ts27subscribeWithSelector<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/subscribeWithSelector', never]], []>28```2930### Mutator3132<!-- prettier-ignore-start -->33```ts34['zustand/subscribeWithSelector', never]35```36<!-- prettier-ignore-end -->3738## Reference3940### `subscribeWithSelector(stateCreatorFn)`4142#### Parameters4344- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.45 Usually, you will return an object with the methods you want to expose.4647#### Returns4849`subscribeWithSelector` returns a state creator function.5051## Usage5253### Subscribing partial state updates5455By subscribing to partial state updates, you register a callback that fires whenever the store's56partial state updates. We can use `subscribe` for external state management.5758```ts59import { createStore } from 'zustand/vanilla'60import { subscribeWithSelector } from 'zustand/middleware'6162type PositionStoreState = { position: { x: number; y: number } }6364type PositionStoreActions = {65 setPosition: (nextPosition: PositionStoreState['position']) => void66}6768type PositionStore = PositionStoreState & PositionStoreActions6970const positionStore = createStore<PositionStore>()(71 subscribeWithSelector((set) => ({72 position: { x: 0, y: 0 },73 setPosition: (position) => set({ position }),74 })),75)7677const $dot = document.getElementById('dot') as HTMLDivElement7879$dot.addEventListener('mouseenter', (event) => {80 const parent = event.currentTarget.parentElement81 const parentWidth = parent.clientWidth82 const parentHeight = parent.clientHeight8384 positionStore.getState().setPosition({85 x: Math.ceil(Math.random() * parentWidth),86 y: Math.ceil(Math.random() * parentHeight),87 })88})8990const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {91 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`92}9394render(positionStore.getInitialState(), positionStore.getInitialState())9596positionStore.subscribe((state) => state.position, render)9798const logger: Parameters<typeof positionStore.subscribe>[0] = (x) => {99 console.log('new x position', { x })100}101102positionStore.subscribe((state) => state.position.x, logger)103```104105Here's the `html` code106107```html108<div109 id="dot-container"110 style="position: relative; width: 100vw; height: 100vh;"111>112 <div113 id="dot"114 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"115 ></div>116</div>117```118119## Troubleshooting120121TBD
added:docs/reference/migrations/migrating-to-v4.md+362 added
1---2title: Migrating to v43nav: 384---56The only breaking changes are in types.7If you are using Zustand with TypeScript8or JSDoc type annotations,9this guide applies.10Otherwise, no migration is required.1112Also, it's recommended to first read13the new [TypeScript Guide](../../learn/guides/advanced-typescript.md),14so that the migration is easier to understand.1516In addition to this migration guide,17you can also check the18[diff](https://github.com/pmndrs/zustand/compare/v3.7.2...v4.0.0?short_path=37e5b4c#diff-c21e24854115b390eccde717da83f91feb2d5927a76c1485e5f0fdd0135c2afa)19of the test files in the Zustand repository from v3 to v4.2021## `create`2223**Applicable imports**2425```ts26import create from 'zustand'27import create from 'zustand/vanilla'28```2930**Change**3132```diff33- create:34- < State35- , StoreSetState = StoreApi<State>["set"]36- , StoreGetState = StoreApi<State>["get"]37- , Store = StoreApi<State>38- >39- (f: ...) => ...40+ create:41+ { <State>(): (f: ...) => ...42+ , <State, Mutators>(f: ...) => ...43+ }44```4546**Migration**4748If you are not passing any type parameters to `create`,49no migration is required.5051If you are using a "leaf" middleware like `combine` or `redux`,52remove all type parameters from `create`.5354Else, replace `create<T, ...>(...)` with `create<T>()(...)`.5556## `StateCreator`5758**Applicable imports**5960```ts61import type { StateCreator } from 'zustand'62import type { StateCreator } from 'zustand/vanilla'63```6465**Change**6667```diff68- type StateCreator69- < State70- , StoreSetState = StoreApi<State>["set"]71- , StoreGetState = StoreApi<State>["get"]72- , Store = StoreApi<State>73- > =74- ...75+ type StateCreator76+ < State77+ , InMutators extends [StoreMutatorIdentifier, unknown][] = []78+ , OutMutators extends [StoreMutatorIdentifier, unknown][] = []79+ , Return = State80+ > =81+ ...82```8384**Migration**8586If you are using `StateCreator`,87you are likely authoring a middleware88or using the "slices" pattern.89For that check the90[Authoring middlewares and advanced usage](../../learn/guides/advanced-typescript.md#authoring-middlewares-and-advanced-usage)91and [Common recipes](../../learn/guides/advanced-typescript.md#common-recipes)92sections of the TypeScript Guide.9394## `PartialState`9596**Applicable imports**9798```ts99import type { PartialState } from 'zustand'100import type { PartialState } from 'zustand/vanilla'101```102103**Change**104105```diff106- type PartialState107- < T extends State108- , K1 extends keyof T = keyof T109- , K2 extends keyof T = K1110- , K3 extends keyof T = K2111- , K4 extends keyof T = K3112- > =113- | (Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)114- | ((state: T) => Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)115+ type PartialState<T> =116+ | Partial<T>117+ | ((state: T) => Partial<T>)118```119120**Migration**121122Replace `PartialState<T, ...>` with `PartialState<T>`123and preferably turn on [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes)124in your `tsconfig.json`:125126```json127{128 "compilerOptions": {129 "exactOptionalPropertyTypes": true130 }131}132```133134We're no longer using the trick to disallow `{ foo: undefined }`135to be assigned to `Partial<{ foo: string }>`.136Instead, we're relying on the users to turn on `exactOptionalPropertyTypes`.137138## `useStore`139140**Applicable imports**141142```ts143import { useStore } from 'zustand'144import { useStore } from 'zustand/react'145```146147**Change**148149```diff150- useStore:151- { <State>(store: StoreApi<State>): State152- , <State, StateSlice>153- ( store: StoreApi<State>154- , selector: StateSelector<State, StateSlice>,155- , equals?: EqualityChecker<StateSlice>156- ): StateSlice157- }158+ useStore:159+ <Store, StateSlice = ExtractState<Store>>160+ ( store: Store161+ , selector?: StateSelector<State, StateSlice>,162+ , equals?: EqualityChecker<StateSlice>163+ )164+ => StateSlice165```166167**Migration**168169If you are not passing any type parameters to `useStore`,170no migration is required.171172If you are,173it's recommended to remove all the type parameters,174or pass the **store** type instead of the **state** type as the first parameter.175176## `UseBoundStore`177178**Applicable imports**179180```ts181import type { UseBoundStore } from 'zustand'182import type { UseBoundStore } from 'zustand/react'183```184185**Change**186187```diff188- type UseBoundStore<189- State,190- Store = StoreApi<State>191- > =192- & { (): T193- , <StateSlice>194- ( selector: StateSelector<State, StateSlice>195- , equals?: EqualityChecker<StateSlice>196- ): U197- }198- & Store199+ type UseBoundStore<Store> =200+ & (<StateSlice = ExtractState<S>>201+ ( selector?: (state: ExtractState<S>) => StateSlice202+ , equals?: (a: StateSlice, b: StateSlice) => boolean203+ ) => StateSlice204+ )205+ & S206```207208**Migration**209210Replace `UseBoundStore<T>` with `UseBoundStore<StoreApi<T>>`,211and `UseBoundStore<T, S>` with `UseBoundStore<S>`212213## `UseContextStore`214215**Applicable imports**216217```ts218import type { UseContextStore } from 'zustand/context'219```220221**Change**222223```diff224- type UseContextStore225```226227**Migration**228229Use `typeof MyContext.useStore` instead230231## `createContext`232233**Applicable imports**234235```ts236import createContext from 'zustand/context'237```238239**Change**240241```diff242 createContext:243- <State, Store = StoreApi<State>>() => ...244+ <Store>() => ...245```246247**Migration**248249Replace `createContext<T>()` with `createContext<StoreApi<T>>()`,250and `createContext<T, S>()` with `createContext<S>()`.251252## `combine`, `devtools`, `subscribeWithSelector`253254**Applicable imports**255256```ts257import { combine } from 'zustand/middleware'258import { devtools } from 'zustand/middleware'259import { subscribeWithSelector } from 'zustand/middleware'260```261262**Change**263264```diff265- combine:266- <T, U>(...) => ...267+ combine:268+ <T, U, Mps, Mcs>(...) => ...269270- devtools:271- <T>(...) => ...272+ devtools:273+ <T, Mps, Mcs>(...) => ...274275- subscribeWithSelector:276- <T>(...) => ...277+ subscribeWithSelector:278+ <T, Mps, Mcs>(...) => ...279```280281**Migration**282283If you are not passing any type parameters284to `combine`, `devtools`, or `subscribeWithSelector`,285no migration is required.286287If you are,288remove all the type parameters,289as they are inferred automatically.290291## `persist`292293**Applicable imports**294295```ts296import { persist } from 'zustand/middleware'297```298299**Change**300301```diff302- persist:303- <T, U = Partial<T>>(...) => ...304+ persist:305+ <T, Mps, Mcs, U = T>(...) => ...306```307308**Migration**309310If you are passing any type parameters,311remove them as they are inferred automatically.312313Next, if you are passing the `partialize` option,314there is no further steps required for migration.315316If you are **not** passing the `partialize` option,317you might see some compilation errors.318If you do not see any,319there is no further migration required.320321The type of partialized state is now `T` instead of `Partial<T>`,322which aligns with the runtime behavior of the default `partialize`,323which is an identity (`s => s`).324325If you see some compilation errors,326you have to find and fix the errors yourself,327because they might be indicative of unsound code.328Alternatively, the workaround will be passing329`s => s as Partial<typeof s>` to `partialize`.330If your partialized state is truly `Partial<T>`,331you should not encounter any bugs.332333The runtime behavior has not changed,334only the types are now correct.335336## `redux`337338**Applicable imports**339340```ts341import { redux } from 'zustand/middleware'342```343344**Change**345346```diff347- redux:348- <T, A>(...) => ...349+ redux:350+ <T, A, Mps, Mcs>(...) => ...351```352353**Migration**354355If you are not passing any type parameters to `redux`,356no migration is required.357358If you are,359remove all the type parameters,360and annotate only the second (action) parameter.361That is, replace `redux<T, A>((state, action) => ..., ...)`362with `redux((state, action: A) => ..., ...)`.
added:docs/reference/migrations/migrating-to-v5.md+241 added
1---2title: How to Migrate to v5 from v43nav: 374---56# How to Migrate to v5 from v478We highly recommend to update to the latest version of v4, before migrating to v5. It will show all deprecation warnings without breaking your app.910## Changes in v51112- Drop default exports13- Drop deprecated features14- Make React 18 the minimum required version15- Make use-sync-external-store a peer dependency (required for `createWithEqualityFn` and `useStoreWithEqualityFn` in `zustand/traditional`)16- Make TypeScript 4.5 the minimum required version17- Drop UMD/SystemJS support18- Organize entry points in the package.json19- Drop ES5 support20- Stricter types when setState's replace flag is set21- Persist middleware behavioral change22- Other small improvements (technically breaking changes)2324## Migration Guide2526### Using custom equality functions such as `shallow`2728The `create` function in v5 does not support customizing equality function.2930If you use custom equality function such as `shallow`,31the easiest migration is to use `createWithEqualityFn`.3233```js34// v435import { create } from 'zustand'36import { shallow } from 'zustand/shallow'3738const useCountStore = create((set) => ({39 count: 0,40 text: 'hello',41 // ...42}))4344const Component = () => {45 const { count, text } = useCountStore(46 (state) => ({47 count: state.count,48 text: state.text,49 }),50 shallow,51 )52 // ...53}54```5556That can be done with `createWithEqualityFn` in v5:5758```bash59npm install use-sync-external-store60```6162```js63// v564import { createWithEqualityFn as create } from 'zustand/traditional'6566// The rest is the same as v467```6869Alternatively, for the `shallow` use case, you can use `useShallow` hook:7071```js72// v573import { create } from 'zustand'74import { useShallow } from 'zustand/shallow'7576const useCountStore = create((set) => ({77 count: 0,78 text: 'hello',79 // ...80}))8182const Component = () => {83 const { count, text } = useCountStore(84 useShallow((state) => ({85 count: state.count,86 text: state.text,87 })),88 )89 // ...90}91```9293### Requiring stable selector outputs9495There is a behavioral change in v5 to match React default behavior.96If a selector returns a new reference, it may cause infinite loops.9798For example, this may cause infinite loops.99100```js101// v4102const [searchValue, setSearchValue] = useStore((state) => [103 state.searchValue,104 state.setSearchValue,105])106```107108The error message will be something like this:109110```plaintext111Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.112```113114To fix it, use the `useShallow` hook, which will return a stable reference.115116```js117// v5118import { useShallow } from 'zustand/shallow'119120const [searchValue, setSearchValue] = useStore(121 useShallow((state) => [state.searchValue, state.setSearchValue]),122)123```124125Here's another example that may cause infinite loops.126127```js128// v4129const action = useMainStore((state) => {130 return state.action ?? () => {}131})132```133134To fix it, make sure the selector function returns a stable reference.135136```js137// v5138139const FALLBACK_ACTION = () => {}140141const action = useMainStore((state) => {142 return state.action ?? FALLBACK_ACTION143})144```145146Alternatively, if you need v4 behavior, `createWithEqualityFn` will do.147148```js149// v5150import { createWithEqualityFn as create } from 'zustand/traditional'151```152153### Stricter types when setState's replace flag is set (Typescript only)154155```diff156- setState:157- (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean | undefined) => void;158+ setState:159+ (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: false) => void;160+ (state: T | ((state: T) => T), replace: true) => void;161```162163If you are not using the `replace` flag, no migration is required.164165If you are using the `replace` flag and it's set to `true`, you must provide a complete state object.166This change ensures that `store.setState({}, true)` (which results in an invalid state) is no longer considered valid.167168**Examples:**169170```ts171// Partial state update (valid)172store.setState({ key: 'value' })173174// Complete state replacement (valid)175store.setState({ key: 'value' }, true)176177// Incomplete state replacement (invalid)178store.setState({}, true) // Error179```180181#### Handling Dynamic `replace` Flag182183If the value of the `replace` flag is dynamic and determined at runtime, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:184185```ts186const replaceFlag = Math.random() > 0.5187const args = [{ bears: 5 }, replaceFlag] as Parameters<188 typeof useBearStore.setState189>190store.setState(...args)191```192193#### Persist middleware no longer stores item at store creation194195Previously, the `persist` middleware stored the initial state during store creation. This behavior has been removed in v5 (and v4.5.5).196197For example, in the following code, the initial state is stored in the storage.198199```js200// v4201import { create } from 'zustand'202import { persist } from 'zustand/middleware'203204const useCountStore = create(205 persist(206 () => ({207 count: Math.floor(Math.random() * 1000),208 }),209 {210 name: 'count',211 },212 ),213)214```215216In v5, this is no longer the case, and you need to explicitly set the state after store creation.217218```js219// v5220import { create } from 'zustand'221import { persist } from 'zustand/middleware'222223const useCountStore = create(224 persist(225 () => ({226 count: 0,227 }),228 {229 name: 'count',230 },231 ),232)233useCountStore.setState({234 count: Math.floor(Math.random() * 1000),235})236```237238## Links239240- https://github.com/pmndrs/zustand/pull/2138241- https://github.com/pmndrs/zustand/pull/2580
added:docs/reference/previous-versions/zustand-v3-create-context.md+145 added
1---2title: createContext from zustand/context3nav: 394---56A special `createContext` is provided since v3.5,7which avoids misusing the store hook.89> **Note**: This function is deprecated in v4 and will be removed in v5. See [Migration](#migration).1011```jsx12import create from 'zustand'13import createContext from 'zustand/context'1415const { Provider, useStore } = createContext()1617const createStore = () => create(...)1819const App = () => (20 <Provider createStore={createStore}>21 ...22 </Provider>23)2425const Component = () => {26 const state = useStore()27 const slice = useStore(selector)28 ...29```3031## createContext usage in real components3233```jsx34import create from "zustand";35import createContext from "zustand/context";3637// Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.3839const { Provider, useStore } = createContext();4041const createStore = () =>42 create((set) => ({43 bears: 0,44 increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),45 removeAllBears: () => set({ bears: 0 })46 }));4748const Button = () => {49 return (50 {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}51 <Provider createStore={createStore}>52 <ButtonChild />53 </Provider>54 );55};5657const ButtonChild = () => {58 const state = useStore();59 return (60 <div>61 {state.bears}62 <button63 onClick={() => {64 state.increasePopulation();65 }}66 >67 +68 </button>69 </div>70 );71};7273export default function App() {74 return (75 <div className="App">76 <Button />77 <Button />78 </div>79 );80}81```8283## createContext usage with initialization from props8485```tsx86import create from 'zustand'87import createContext from 'zustand/context'8889const { Provider, useStore } = createContext()9091export default function App({ initialBears }) {92 return (93 <Provider94 createStore={() =>95 create((set) => ({96 bears: initialBears,97 increase: () => set((state) => ({ bears: state.bears + 1 })),98 }))99 }100 >101 <Button />102 </Provider>103 )104}105```106107## Migration108109Discussion: https://github.com/pmndrs/zustand/discussions/1276110111Here's the new context usage with v4 API.112113```jsx114import { createContext, useContext, useRef } from 'react'115import { createStore, useStore } from 'zustand'116117const StoreContext = createContext(null)118119const StoreProvider = ({ children }) => {120 const storeRef = useRef()121 if (storeRef.current === null) {122 storeRef.current = createStore((set) => ({123 // ...124 }))125 }126 return (127 <StoreContext.Provider value={storeRef.current}>128 {children}129 </StoreContext.Provider>130 )131}132133const useStoreInContext = (selector) => {134 const store = useContext(StoreContext)135 if (!store) {136 throw new Error('Missing StoreProvider')137 }138 return useStore(store, selector)139}140```141142Or reach out to some third-party libraries that provide Zustand v3-like APIs:143144- <https://github.com/charkour/zustand-di>145- <https://github.com/arvinxx/zustand-utils>
added:docs/reference/index.md+53 added
1---2title: Reference3description: API-first reference for stores, hooks, middlewares, and integrations.4---56## APIs78Core functions for creating and configuring stores.910- [`create`](/reference/apis/create.md) — Create a store bound to React via hooks.11- [`createStore`](/reference/apis/create-store.md) — Create a standalone store without React.12- [`createWithEqualityFn`](/reference/apis/create-with-equality-fn.md) — Like `create`, but with a custom equality function.13- [`shallow`](/reference/apis/shallow.md) — Utility for shallow comparison of objects and arrays.1415## Hooks1617React hooks for reading and subscribing to store state.1819- [`useStore`](/reference/hooks/use-store.md) — Access and subscribe to a vanilla store from a React component.20- [`useStoreWithEqualityFn`](/reference/hooks/use-store-with-equality-fn.md) — Like `useStore`, but with a custom equality function.21- [`useShallow`](/reference/hooks/use-shallow.md) — Derive a stable reference from a selector using shallow comparison.2223## Middlewares2425Composable middleware functions for extending store behavior.2627- [`persist`](/reference/middlewares/persist.md) — Persist and rehydrate state using `localStorage` or a custom storage engine.28- [`devtools`](/reference/middlewares/devtools.md) — Connect a store to Redux DevTools for time-travel debugging.29- [`redux`](/reference/middlewares/redux.md) — Use a reducer and dispatch pattern similar to Redux.30- [`immer`](/reference/middlewares/immer.md) — Write state updates with mutable syntax using Immer.31- [`combine`](/reference/middlewares/combine.md) — Combine separate state slices into a single store with inferred types.32- [`subscribeWithSelector`](/reference/middlewares/subscribe-with-selector.md) — Subscribe to a slice of state with selector and equality support.3334## Integrations3536In-depth guides for using Zustand alongside third-party libraries.3738- [Persisting store data](/reference/integrations/persisting-store-data.md) — Detailed guide to the `persist` middleware and storage adapters.39- [Immer middleware](/reference/integrations/immer-middleware.md) — Detailed guide to the `immer` middleware.40- [Third-party libraries](/reference/integrations/third-party-libraries.md) — Using Zustand with other libraries in the ecosystem.4142## Migrations4344Upgrade guides between major versions.4546- [Migrating to v5](/reference/migrations/migrating-to-v5.md) — How to upgrade from Zustand v4.47- [Migrating to v4](/reference/migrations/migrating-to-v4.md) — How to upgrade from Zustand v3.4849## Previous versions5051APIs that existed in older versions of Zustand and are no longer recommended for new code.5253- [createContext (v3)](/reference/previous-versions/zustand-v3-create-context.md) — The `createContext` export from `zustand/context`, deprecated in v4 and removed in v5.
deleted:docs/bear.jpgbinary

A binary file, deleted.

deleted:docs/favicon.icobinary

A binary file, deleted.

added:docs/index.md+27 added
1---2pageType: home34hero:5 text: Bear necessities for React state6 tagline: A tiny, predictable store with hooks-first ergonomics and escape hatches that stay out of your way.7 actions:8 - theme: brand9 text: Introduction10 link: /getting-started/introduction11 - theme: alt12 text: Quick Start13 link: /learn/14features:15 - title: Minimal API, fast adoption16 details: Create a store with a single hook, subscribe with selectors, and avoid boilerplate or providers.17 - title: Safe under React concurrency18 details: Built to avoid zombie children and tearing issues while keeping renders predictable.19 - title: Works across React and vanilla20 details: Share stores between React, React Native, and non-React environments with the same API surface.21 - title: Batteries included22 details: Opt into devtools, persistence, Redux-style middleware, and Immer without changing your mental model.23 - title: TypeScript-first ergonomics24 details: Strongly typed helpers and patterns so your state and actions stay inferred.25 - title: Small footprint26 details: Tiny bundle size with zero config and performance that keeps pace in production.27---
deleted:docs/llms.txt-51 removed
1# Zustand23Zustand is a fast, minimal state management library for React and JavaScript. It provides a simple API without context providers or boilerplate.45## Docs67- [Official Docs](https://zustand.docs.pmnd.rs): Complete reference for Zustand.8- [Getting Started](https://zustand.docs.pmnd.rs/getting-started/introduction): Learn the basics and create your first store.910## Core API1112- [createStore](https://zustand.docs.pmnd.rs/apis/create-store): Create a standalone store without React.13- [shallow](https://zustand.docs.pmnd.rs/apis/shallow): Utility for shallow comparison of `objects`.1415## Middlewares1617- [combine](https://zustand.docs.pmnd.rs/middlewares/combine): Combine multiple slices into a single store.18- [devtools](https://zustand.docs.pmnd.rs/middlewares/devtools): Debug state changes using Redux DevTools.19- [immer](https://zustand.docs.pmnd.rs/middlewares/immer): Use `Immer` for immutable state updates.20- [persist](https://zustand.docs.pmnd.rs/middlewares/persist): Persist state to `localStorage` or other storage engines.21- [redux](https://zustand.docs.pmnd.rs/middlewares/redux): Use a reducer-style setup similar to `Redux`.22- [subscribeWithSelector](https://zustand.docs.pmnd.rs/middlewares/subscribe-with-selector): Subscribe to specific slices with selector support.2324## React Bindings2526- [create](https://zustand.docs.pmnd.rs/apis/create): Bind a store to React for use with hooks.27- [createWithEqualityFn](https://zustand.docs.pmnd.rs/apis/create-with-equality-fn): Like `create`, but allows custom equality functions.2829## React Hooks3031- [useStore](https://zustand.docs.pmnd.rs/hooks/use-store): Access and subscribe to store state.32- [useStoreWithEqualityFn](https://zustand.docs.pmnd.rs/hooks/use-store-with-equality-fn): Same as `useStore`, but with custom equality checks.33- [useShallow](https://zustand.docs.pmnd.rs/hooks/use-shallow): Use selectors with shallow equality comparison.3435## Migration Guides3637- [Migrate to v4](https://zustand.docs.pmnd.rs/migrations/migrating-to-v4): How to upgrade from Zustand v3.38- [Migrate to v5](https://zustand.docs.pmnd.rs/migrations/migrating-to-v5): How to upgrade from Zustand v4.3940## Tutorials4142- [Tic-Tac-Toe Guide](https://zustand.docs.pmnd.rs/guides/tutorial-tic-tac-toe): Build a game using Zustand state.4344## More4546- [Third-party Libraries](https://zustand.docs.pmnd.rs/integrations/third-party-libraries): Integrations with third-party libraries.47- [Zustand vs Other Libraries](https://zustand.docs.pmnd.rs/getting-started/comparison): Comparison with other state management libraries.48- [TypeScript](https://zustand.docs.pmnd.rs/guides/typescript): Guide to using Zustand with TypeScript.49- [Testing](https://zustand.docs.pmnd.rs/guides/testing): Best practices for testing Zustand stores.50- [Next.js](https://zustand.docs.pmnd.rs/guides/nextjs): Using Zustand with Next.js for state management.51- [Slices Pattern](https://zustand.docs.pmnd.rs/guides/slices-pattern): Organizing state into slices for scalability and maintainability.