Update docs content (#2760)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Update docs content * Update docs content * Update docs content * Update docs content * Update docs content * WIP * WIP * Update docs content * Update create.md * Update create-with-equality-fn.md * Update create-store.md * Update use-store.md * Update use-store-with-equality-fn.md
authored by Danilo Britto · committed by GitHub · parent 055dcdc · Browse files · 13 files·+2094 added−281 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+2094 added−281 removed
- other:+2094 added−281 removed
Provenance
- Commit
211f108- Tree
1ed6e20- Author
Danilo Britto <dbritto.dev@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
055dcdc
13 files changed+2094 added−281 removed
modified:docs/apis/create-store.md+56 added-80 removed
5 unmodified lines6 7 `createStore` lets you create a vanilla store that exposes API utilities.8 9 ```js10-createStore(stateCreatorFn)10+const someStore = createStore(stateCreatorFn)11 ```12 13-- [Reference](#reference)13+- [Types](#types)14 - [Signature](#createstore-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)20- - [Updating state with no store actions](#updating-state-with-no-store-actions)21 - [Subscribing to state updates](#subscribing-to-state-updates)22 - [Troubleshooting](#troubleshooting)23 - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)24 25-## Reference25+## Types26 27-### `createStore` Signature27+### Signature28 29 ```ts30 createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>31 ```32 33+## Reference34+35+### `createStore(stateCreatorFn)`36+37 #### Parameters38 35-- `stateCreatorFn`: A function that takes `set` function, `get` function and `api` as arguments.39+- `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.41 42 #### Returns43 3 unmodified lines47 ## Usage48 49 ### Updating state based on previous state50 47-This example shows how you can support **updater functions** for your **actions**.51+This example shows how you can support **updater functions** within **actions**.52 53 ```tsx54 import { createStore } from 'zustand/vanilla'55 10 unmodified lines66 type AgeStore = AgeStoreState & AgeStoreActions67 68 const ageStore = createStore<AgeStore>()((set) => ({69 age: 42,66- setAge: (nextAge) => {70+ setAge: (nextAge) =>71 set((state) => ({72 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,69- }))70- },73+ })),74 }))75 76 function increment() {77 ageStore.getState().setAge((currentAge) => currentAge + 1)59 unmodified lines137 $dotContainer.addEventListener('pointermove', (event) => {138 xStore.setState(event.clientX, true)139 })140 138-const render: Parameters<typeof xStore.subscribe>[0] = (state) => {139- const position = { y: 0, x: state }140-141- $dot.style.transform = `translate(${position.x}px, ${position.y}px)`141+const render: Parameters<typeof xStore.subscribe>[0] = (x) => {142+ $dot.style.transform = `translate(${x}px, 0)`143 }144 145 render(xStore.getInitialState(), xStore.getInitialState())146 27 unmodified lines174 175 ```ts176 import { createStore } from 'zustand/vanilla'177 177-type PositionStoreState = { x: number; y: number }178+type PositionStoreState = { position: { x: number; y: number } }179 180 type PositionStoreActions = {180- setPosition: (nextPosition: Partial<PositionStoreState>) => void181+ setPosition: (nextPosition: PositionStoreState['position']) => void182 }183 184 type PositionStore = PositionStoreState & PositionStoreActions185 186 const positionStore = createStore<PositionStore>()((set) => ({186- x: 0,187- y: 0,188- setPosition: (nextPosition) => {189- set(nextPosition)190- },187+ position: { x: 0, y: 0 },188+ setPosition: (position) => set({ position }),189 }))190 191 const $dotContainer = document.getElementById('dot-container') as HTMLDivElement192 const $dot = document.getElementById('dot') as HTMLDivElement5 unmodified lines198 })199 })200 201 const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {204- const position = { x: state.x, y: state.y }205-206- $dot.style.transform = `translate(${position.x}px, ${position.y}px)`202+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`203 }204 205 render(positionStore.getInitialState(), positionStore.getInitialState())206 43 unmodified lines250 $dotContainer.addEventListener('pointermove', (event) => {251 positionStore.setState([event.clientX, event.clientY], true)252 })253 258-const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {259- const position = { x: state[0], y: state[1] }260-261- $dot.style.transform = `translate(${position.x}px, ${position.y}px)`254+const render: Parameters<typeof positionStore.subscribe>[0] = ([x, y]) => {255+ $dot.style.transform = `translate(${x}px, ${y}px)`256 }257 258 render(positionStore.getInitialState(), positionStore.getInitialState())259 21 unmodified lines281 282 ```ts283 import { createStore } from 'zustand/vanilla'284 291-type PositionStoreState = { x: number; y: number }285+type PositionStoreState = { position: { x: number; y: number } }286 287 type PositionStoreActions = {294- setPosition: (nextPosition: Partial<PositionStoreState>) => void288+ setPosition: (nextPosition: PositionStoreState['position']) => void289 }290 291 type PositionStore = PositionStoreState & PositionStoreActions292 293 const positionStore = createStore<PositionStore>()((set) => ({300- x: 0,301- y: 0,302- setPosition: (nextPosition) => {303- set(nextPosition)304- },294+ position: { x: 0, y: 0 },295+ setPosition: (position) => set({ position }),296 }))297 298 const $dot = document.getElementById('dot') as HTMLDivElement299 8 unmodified lines308 })309 })310 311 const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {321- const position = { x: state.x, y: state.y }322-323- $dot.style.transform = `translate(${position.x}px, ${position.y}px)`312+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`313 }314 315 render(positionStore.getInitialState(), positionStore.getInitialState())316 317 positionStore.subscribe(render)318 319 const logger: Parameters<typeof positionStore.subscribe>[0] = (state) => {331- console.log('new position', { position: { x: state.x, y: state.x } })320+ console.log('new position', { position: state.position })321 }322 323 positionStore.subscribe(logger)324 ```26 unmodified lines351 ```ts352 import { createStore } from 'zustand/vanilla'353 354 type PersonStoreState = {366- firstName: string367- lastName: string368- email: string355+ person: { firstName: string; lastName: string; email: string }356 }357 358 type PersonStoreActions = {372- setPerson: (nextPerson: Partial<PersonStoreState>) => void359+ setPerson: (nextPerson: PersonStoreState['person']) => void360 }361 362 type PersonStore = PersonStoreState & PersonStoreActions363 364 const personStore = createStore<PersonStore>()((set) => ({378- firstName: 'Barbara',379- lastName: 'Hepworth',380- email: 'bhepworth@sculpture.com',381- setPerson: (nextPerson) => {382- set(nextPerson)365+ person: {366+ firstName: 'Barbara',367+ lastName: 'Hepworth',368+ email: 'bhepworth@sculpture.com',369 },370+ setPerson: (person) => set({ person }),371 }))372 373 const $firstNameInput = document.getElementById(374 'first-name',2 unmodified lines377 const $emailInput = document.getElementById('email') as HTMLInputElement378 const $result = document.getElementById('result') as HTMLDivElement379 380 function handleFirstNameChange(event: Event) {394- personStore.getState().firstName = (event.target as any).value381+ personStore.getState().person.firstName = (event.target as any).value382 }383 384 function handleLastNameChange(event: Event) {398- personStore.getState().lastName = (event.target as any).value385+ personStore.getState().person.lastName = (event.target as any).value386 }387 388 function handleEmailChange(event: Event) {402- personStore.getState().email = (event.target as any).value389+ personStore.getState().person.email = (event.target as any).value390 }391 392 $firstNameInput.addEventListener('input', handleFirstNameChange)393 $lastNameInput.addEventListener('input', handleLastNameChange)394 $emailInput.addEventListener('input', handleEmailChange)395 396 const render: Parameters<typeof personStore.subscribe>[0] = (state) => {410- const person = {411- firstName: state.firstName,412- lastName: state.lastName,413- email: state.email,414- }397+ $firstNameInput.value = state.person.firstName398+ $lastNameInput.value = state.person.lastName399+ $emailInput.value = state.person.email400 416- $firstNameInput.value = person.firstName417- $lastNameInput.value = person.lastName418- $emailInput.value = person.email419-420- $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`401+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`402 }403 404 render(personStore.getInitialState(), personStore.getInitialState())405 46 unmodified lines452 ```ts {32-34,38-40,44-46}453 import { createStore } from 'zustand/vanilla'454 455 type PersonStoreState = {475- firstName: string476- lastName: string477- email: string456+ person: { firstName: string; lastName: string; email: string }457 }458 459 type PersonStoreActions = {481- setPerson: (nextPerson: Partial<PersonStoreState>) => void460+ setPerson: (nextPerson: PersonStoreState['person']) => void461 }462 463 type PersonStore = PersonStoreState & PersonStoreActions464 465 const personStore = createStore<PersonStore>()((set) => ({487- firstName: 'Barbara',488- lastName: 'Hepworth',489- email: 'bhepworth@sculpture.com',490- setPerson: (nextPerson) => {491- set(nextPerson)466+ person: {467+ firstName: 'Barbara',468+ lastName: 'Hepworth',469+ email: 'bhepworth@sculpture.com',470 },471+ setPerson: (person) => set({ person }),472 }))473 474 const $firstNameInput = document.getElementById(475 'first-name',3 unmodified lines479 const $result = document.getElementById('result') as HTMLDivElement480 481 function handleFirstNameChange(event: Event) {482 personStore.getState().setPerson({483+ ...personStore.getState().person,484 firstName: (event.target as any).value,485 })486 }487 488 function handleLastNameChange(event: Event) {489 personStore.getState().setPerson({490+ ...personStore.getState().person,491 lastName: (event.target as any).value,492 })493 }494 495 function handleEmailChange(event: Event) {496 personStore.getState().setPerson({497+ ...personStore.getState().person,498 email: (event.target as any).value,499 })500 }501 1 unmodified line503 $lastNameInput.addEventListener('input', handleLastNameChange)504 $emailInput.addEventListener('input', handleEmailChange)505 506 const render: Parameters<typeof personStore.subscribe>[0] = (state) => {525- const person = {526- firstName: state.firstName,527- lastName: state.lastName,528- email: state.email,529- }507+ $firstNameInput.value = state.person.firstName508+ $lastNameInput.value = state.person.lastName509+ $emailInput.value = state.person.email510 531- $firstNameInput.value = person.firstName532- $lastNameInput.value = person.lastName533- $emailInput.value = person.email534-535- $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`511+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`512 }513 514 render(personStore.getInitialState(), personStore.getInitialState())515 2 unmodified linesmodified:docs/apis/create-with-equality-fn.md+63 added-82 removed
7 unmodified lines8 However, it offers a way to define a custom equality check. This allows for more granular control9 over when components re-render, improving performance and responsiveness.10 11 ```js12-createWithEqualityFn(stateCreatorFn, equalityFn)12+const useSomeStore = createWithEqualityFn(stateCreatorFn, equalityFn)13 ```14 15-- [Reference](#reference)15+- [Types](#types)16 - [Signature](#createwithequalityfn-signature)17+- [Reference](#reference)18 - [Usage](#usage)19 - [Updating state based on previous state](#updating-state-based-on-previous-state)20 - [Updating Primitives in State](#updating-primitives-in-state)21 - [Updating Objects in State](#updating-objects-in-state)2 unmodified lines24 - [Subscribing to state updates](#subscribing-to-state-updates)25 - [Troubleshooting](#troubleshooting)26 - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)27 27-## Reference28+## Types29 29-### `createWithEqualityFn` Signature30+### Signature31 32 ```ts33 createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, equalityFn?: (a: T, b: T) => boolean): UseBoundStore<StoreApi<T>>34 ```35 36+## Reference37+38+### `createWithEqualityFn(stateCreatorFn)`39+40 #### Parameters41 37-- `stateCreatorFn`: A function that takes `set` function, `get` function and `api` as arguments.42+- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.43 Usually, you will return an object with the methods you want to expose.44 - **optional** `equalityFn`: Defaults to `Object.is`. A function that lets you skip re-renders.45 46 #### Returns2 unmodified lines49 lets you return data that is based on current state, using a selector function, and lets you skip50 re-renders using an equality function. It should take a selector function, and an equality function51 as arguments.52 53+## Usage54+55 ### Updating state based on previous state56 57 To update a state based on previous state we should use **updater functions**. Read more58 about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).59 53-This example shows how you can support **updater functions** for your **actions**.60+This example shows how you can support **updater functions** within **actions**.61 62 ```tsx63 import { createWithEqualityFn } from 'zustand/traditional'64 import { shallow } from 'zustand/vanilla/shallow'12 unmodified lines77 78 const useAgeStore = createWithEqualityFn<AgeStore>()(79 (set) => ({80 age: 42,74- setAge: (nextAge) => {81+ setAge: (nextAge) =>82 set((state) => ({83 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,77- }))78- },84+ })),85 }),86 shallow,87 )88 98 unmodified lines187 ```tsx188 import { createWithEqualityFn } from 'zustand/traditional'189 import { shallow } from 'zustand/vanilla/shallow'190 185-type PositionStoreState = { x: number; y: number }191+type PositionStoreState = { position: { x: number; y: number } }192 193 type PositionStoreActions = {188- setPosition: (nextPosition: Partial<PositionStoreState>) => void194+ setPosition: (nextPosition: PositionStoreState['position']) => void195 }196 197 type PositionStore = PositionStoreState & PositionStoreActions198 199 const usePositionStore = createWithEqualityFn<PositionStore>()(200 (set) => ({195- x: 0,196- y: 0,197- setPosition: (nextPosition) => {198- set(nextPosition)199- },201+ position: { x: 0, y: 0 },202+ setPosition: (position) => set({ position }),203 }),204 shallow,205 )206 207 export default function MovingDot() {205- const [position, setPosition] = usePositionStore((state) => [206- { x: state.x, y: state.y },207- state.setPosition,208- ])208+ const position = usePositionStore((state) => state.position)209+ const setPosition = usePositionStore((state) => state.setPosition)210 211 return (212 <div213 onPointerMove={(e) => {53 unmodified lines267 )268 269 export default function MovingDot() {270 const [x, y] = usePositionStore()271+ const position = { x, y }272 const setPosition: typeof usePositionStore.setState = (nextPosition) => {273 usePositionStore.setState(nextPosition, true)274 }273- const position = { x, y }275 276 return (277 <div278 onPointerMove={(e) => {91 unmodified lines370 import { useEffect } from 'react'371 import { createWithEqualityFn } from 'zustand/traditional'372 import { shallow } from 'zustand/vanilla/shallow'373 373-type PositionStoreState = { x: number; y: number }374+type PositionStoreState = { position: { x: number; y: number } }375 376 type PositionStoreActions = {376- setPosition: (nextPosition: Partial<PositionStoreState>) => void377+ setPosition: (nextPosition: PositionStoreState['position']) => void378 }379 380 type PositionStore = PositionStoreState & PositionStoreActions381 382 const usePositionStore = createWithEqualityFn<PositionStore>()(383 (set) => ({383- x: 0,384- y: 0,385- setPosition: (nextPosition) => {386- set(nextPosition)387- },384+ position: { x: 0, y: 0 },385+ setPosition: (nextPosition) => set(nextPosition),386 }),387 shallow,388 )389 390 export default function MovingDot() {393- const [position, setPosition] = usePositionStore((state) => [394- { x: state.x, y: state.y },395- state.setPosition,396- ])391+ const position = usePositionStore((state) => state.position)392+ const setPosition = usePositionStore((state) => state.setPosition)393 394 useEffect(() => {399- const unsubscribePositionStore = usePositionStore.subscribe(({ x, y }) => {400- console.log('new position', { position: { x, y } })401- })395+ const unsubscribePositionStore = usePositionStore.subscribe(396+ ({ position }) => {397+ console.log('new position', { position })398+ },399+ )400 401 return () => {402 unsubscribePositionStore()403 }49 unmodified lines453 import { createWithEqualityFn } from 'zustand/traditional'454 import { shallow } from 'zustand/vanilla/shallow'455 456 type PersonStoreState = {459- firstName: string460- lastName: string461- email: string457+ person: { firstName: string; lastName: string; email: string }458 }459 460 type PersonStoreActions = {465- setPerson: (nextPerson: Partial<PersonStoreState>) => void461+ setPerson: (nextPerson: PersonStoreState['person']) => void462 }463 464 type PersonStore = PersonStoreState & PersonStoreActions465 466 const usePersonStore = createWithEqualityFn<PersonStore>()(467 (set) => ({472- firstName: 'Barbara',473- lastName: 'Hepworth',474- email: 'bhepworth@sculpture.com',475- setPerson: (nextPerson) => {476- set(nextPerson)468+ person: {469+ firstName: 'Barbara',470+ lastName: 'Hepworth',471+ email: 'bhepworth@sculpture.com',472 },473+ setPerson: (person) => set({ person }),474 }),475 shallow,476 )477 478 export default function Form() {483- const [person] = usePersonStore((state) => [484- {485- firstName: state.firstName,486- lastName: state.lastName,487- email: state.email,488- },489- state.setPerson,490- ])479+ const person = usePersonStore((state) => state.person)480+ const setPerson = usePersonStore((state) => state.setPerson)481 492- function handleFirstNameChange(e) {482+ function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {483 person.firstName = e.target.value484 }485 496- function handleLastNameChange(e) {486+ function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {487 person.lastName = e.target.value488 }489 500- function handleEmailChange(e) {490+ function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {491 person.email = e.target.value492 }493 494 return (28 unmodified lines523 `setPerson`. But here you want to also copy the existing data into it because only one of the524 fields has changed:525 526 ```ts537-setPerson({538- firstName: e.target.value, // New first name from the input539-})527+setPerson({ ...person, firstName: e.target.value }) // New first name from the input528 ```529 530 > [!NOTE]531 > We don’t need to copy every property separately due to `set` function performing shallow merge by3 unmodified lines535 536 Notice how you didn’t declare a separate state variable for each input field. For large forms,537 keeping all data grouped in an object is very convenient—as long as you update it correctly!538 551-```tsx {39,43,47}539+```tsx {32,36,40}540+import { type ChangeEvent } from 'react'541 import { createWithEqualityFn } from 'zustand/traditional'542 import { shallow } from 'zustand/vanilla/shallow'543 544 type PersonStoreState = {556- firstName: string557- lastName: string558- email: string545+ person: { firstName: string; lastName: string; email: string }546 }547 548 type PersonStoreActions = {562- setPerson: (nextPerson: Partial<PersonStoreState>) => void549+ setPerson: (nextPerson: PersonStoreState['person']) => void550 }551 552 type PersonStore = PersonStoreState & PersonStoreActions553 554 const usePersonStore = createWithEqualityFn<PersonStore>()(555 (set) => ({569- firstName: 'Barbara',570- lastName: 'Hepworth',571- email: 'bhepworth@sculpture.com',572- setPerson: (nextPerson) => {573- set(nextPerson)556+ person: {557+ firstName: 'Barbara',558+ lastName: 'Hepworth',559+ email: 'bhepworth@sculpture.com',560 },561+ setPerson: (person) => set({ person }),562 }),563 shallow,564 )565 566 export default function Form() {580- const [person, setPerson] = usePersonStore((state) => [581- {582- firstName: state.firstName,583- lastName: state.lastName,584- email: state.email,585- },586- state.setPerson,587- ])567+ const person = usePersonStore((state) => state.person)568+ const setPerson = usePersonStore((state) => state.setPerson)569 589- function handleFirstNameChange(e) {590- setPerson({ firstName: e.target.value })570+ function handleFirstNameChange(e: ChangeEvent<HTLMInputElement>) {571+ setPerson({ ...person, firstName: e.target.value })572 }573 593- function handleLastNameChange(e) {594- setPerson({ lastName: e.target.value })574+ function handleLastNameChange(e: ChangeEvent<HTLMInputElement>) {575+ setPerson({ ...person, lastName: e.target.value })576 }577 597- function handleEmailChange(e) {598- setPerson({ email: e.target.value })578+ function handleEmailChange(e: ChangeEvent<HTLMInputElement>) {579+ setPerson({ ...person, email: e.target.value })580 }581 582 return (583 <>19 unmodified linesmodified:docs/apis/create.md+51 added-72 removed
5 unmodified lines6 7 `create` lets you create a React Hook with API utilities attached.8 9 ```js10-create(stateCreatorFn)10+const useSomeStore = create(stateCreatorFn)11 ```12 13-- [Reference](#reference)13+- [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)2 unmodified lines22 - [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)25 25-## Reference26+## Types27 27-### `create` Signature28+### Signature29 30 ```ts31 create<T>()(stateCreatorFn: StateCreator<T, [], []>): UseBoundStore<StoreApi<T>>32 ```33 34+## Reference35+36+### `create(stateCreatorFn)`37+38 #### Parameters39 35-- `stateCreatorFn`: A function that takes `set` function, `get` function and `api` as arguments.40+- `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.42 43 #### Returns44 7 unmodified lines52 53 To update a state based on previous state we should use **updater functions**. Read more54 about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).55 51-This example shows how you can support **updater functions** for your **actions**.56+This example shows how you can support **updater functions** within **actions**.57 58 ```tsx59 import { create } from 'zustand'60 115 unmodified lines176 177 ```tsx178 import { create } from 'zustand'179 175-type PositionStoreState = { x: number; y: number }180+type PositionStoreState = { position: { x: number; y: number } }181 182 type PositionStoreActions = {178- setPosition: (nextPosition: Partial<PositionStoreState>) => void183+ setPosition: (nextPosition: PositionStoreState['position']) => void184 }185 186 type PositionStore = PositionStoreState & PositionStoreActions187 188 const usePositionStore = create<PositionStore>()((set) => ({184- x: 0,185- y: 0,186- setPosition: (nextPosition) => {187- set(nextPosition)188- },189+ position: { x: 0, y: 0 },190+ setPosition: (nextPosition) => set(nextPosition),191 }))192 193 export default function MovingDot() {192- const [position, setPosition] = usePositionStore((state) => [193- { x: state.x, y: state.y },194- state.setPosition,195- ])194+ const position = usePositionStore((state) => state.position)195+ const setPosition = usePositionStore((state) => state.setPosition)196 197 return (198 <div199 onPointerMove={(e) => {150 unmodified lines350 ```tsx351 import { useEffect } from 'react'352 import { create } from 'zustand'353 354-type PositionStoreState = { x: number; y: number }354+type PositionStoreState = { position: { x: number; y: number } }355 356 type PositionStoreActions = {357- setPosition: (nextPosition: Partial<PositionStoreState>) => void357+ setPosition: (nextPosition: PositionStoreState['position']) => void358 }359 360 type PositionStore = PositionStoreState & PositionStoreActions361 362 const usePositionStore = create<PositionStore>()((set) => ({363- x: 0,364- y: 0,365- setPosition: (nextPosition) => {366- set(nextPosition)367- },363+ position: { x: 0, y: 0 },364+ setPosition: (nextPosition) => set(nextPosition),365 }))366 367 export default function MovingDot() {371- const [position, setPosition] = usePositionStore((state) => [372- { x: state.x, y: state.y },373- state.setPosition,374- ])368+ const position = usePositionStore((state) => state.position)369+ const setPosition = usePositionStore((state) => state.setPosition)370 371 useEffect(() => {377- const unsubscribePositionStore = usePositionStore.subscribe(({ x, y }) => {378- console.log('new position', { position: { x, y } })379- })372+ const unsubscribePositionStore = usePositionStore.subscribe(373+ ({ position }) => {374+ console.log('new position', { position })375+ },376+ )377 378 return () => {379 unsubscribePositionStore()380 }63 unmodified lines444 const usePersonStore = create<PersonStore>()((set) => ({445 firstName: 'Barbara',446 lastName: 'Hepworth',447 email: 'bhepworth@sculpture.com',451- setPerson: (nextPerson) => {452- set(nextPerson)453- },448+ setPerson: (nextPerson) => set(nextPerson),449 }))450 451 export default function Form() {457- const [person] = usePersonStore((state) => [458- {459- firstName: state.firstName,460- lastName: state.lastName,461- email: state.email,462- },463- state.setPerson,464- ])452+ const person = usePersonStore((state) => person)453+ const setPerson = usePersonStore((state) => setPerson)454 466- function handleFirstNameChange(e) {455+ function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {456 person.firstName = e.target.value457 }458 470- function handleLastNameChange(e) {459+ function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {460 person.lastName = e.target.value461 }462 474- function handleEmailChange(e) {463+ function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {464 person.email = e.target.value465 }466 467 return (28 unmodified lines496 `setPerson`. But here you want to also copy the existing data into it because only one of the497 fields has changed:498 499 ```ts511-setPerson({512- firstName: e.target.value, // New first name from the input513-})500+setPerson({ ...person, firstName: e.target.value }) // New first name from the input501 ```502 503 > [!NOTE]504 > We don’t need to copy every property separately due to `set` function performing shallow merge by3 unmodified lines508 509 Notice how you didn’t declare a separate state variable for each input field. For large forms,510 keeping all data grouped in an object is very convenient—as long as you update it correctly!511 525-```tsx {35,39,43}512+```tsx {27,31,35}513 import { create } from 'zustand'514 515 type PersonStoreState = {529- firstName: string530- lastName: string531- email: string516+ person: { firstName: string; lastName: string; email: string }517 }518 519 type PersonStoreActions = {535- setPerson: (nextPerson: Partial<PersonStoreState>) => void520+ setPerson: (nextPerson: PersonStoreState['person']) => void521 }522 523 type PersonStore = PersonStoreState & PersonStoreActions524 525 const usePersonStore = create<PersonStore>()((set) => ({541- firstName: 'Barbara',542- lastName: 'Hepworth',543- email: 'bhepworth@sculpture.com',544- setPerson: (nextPerson) => {545- set(nextPerson)526+ person: {527+ firstName: 'Barbara',528+ lastName: 'Hepworth',529+ email: 'bhepworth@sculpture.com',530 },531+ setPerson: (nextPerson) => set(nextPerson),532 }))533 534 export default function Form() {550- const [person, setPerson] = usePersonStore((state) => [551- {552- firstName: state.firstName,553- lastName: state.lastName,554- email: state.email,555- },556- state.setPerson,557- ])535+ const person = usePersonStore((state) => state.person)536+ const setPerson = usePersonStore((state) => state.setPerson)537 559- function handleFirstNameChange(e) {560- setPerson({ firstName: e.target.value })538+ function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {539+ setPerson({ ...person, firstName: e.target.value })540 }541 563- function handleLastNameChange(e) {564- setPerson({ lastName: e.target.value })542+ function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {543+ setPerson({ ...person, lastName: e.target.value })544 }545 567- function handleEmailChange(e) {568- setPerson({ email: e.target.value })546+ function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {547+ setPerson({ ...person, email: e.target.value })548 }549 550 return (551 <>19 unmodified linesmodified:docs/apis/shallow.md+9 added-4 removed
10 unmodified lines11 > [!NOTE]12 > Shallow lets you perform quick comparisons, but keep its limitations in mind.13 14 ```js15-shallow(a, b)15+const equal = shallow(a, b)16 ```17 18-- [Reference](#reference)18+- [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 28-## Reference29+## Types30 30-### `shallow` Signature31+### Signature32 33 ```ts34 shallow<T>(a: T, b: T): boolean35 ```36 37+## Reference38+39+### `shallow(a, b)`40+41 #### Parameters42 43 - `a`: The first value.44 - `b`: The second value.182 unmodified linesmodified:docs/hooks/use-shallow.md+8 added-6 removed
5 unmodified lines6 7 `useShallow` is a React Hook that lets you optimize re-renders.8 9 ```js10-useShallow(selector)10+const memoizedSelector = useShallow(selector)11 ```12 13+- [Types](#types)14+ - [Signature](#signature)15 - [Reference](#reference)14- - [Signature](#useshallow-signature)16 - [Usage](#usage)17 - [Writing a memoized selector](#writing-a-memoized-selector)18 - [Troubleshooting](#troubleshooting)18- - TBD19 20-## Reference20+### Signature21 22-### `useShallow` Signature23-22 ```ts23 useShallow<T, U = T>(selectorFn: (state: T) => U): (state: T) => U24 ```25 26+## Reference27+28+### `useShallow(selectorFn)`29+30 #### Parameters31 32 - `selectorFn`: A function that lets you return data that is based on current state.33 231 unmodified linesmodified:docs/hooks/use-store-with-equality-fn.md+13 added-19 removed
7 unmodified lines8 `useStore`. However, it offers a way to define a custom equality check. This allows for more9 granular control over when components re-render, improving performance and responsiveness.10 11 ```js12-useStoreWithEqualityFn(storeApi, selectorFn, equalityFn)12+const someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)13 ```14 15+- [Types](#types)16+ - [Signature](#signature)17 - [Reference](#reference)16- - [Signature](#usestorewithequalityfn-signature)18 - [Usage](#usage)19 - [Use a vanilla store in React](#use-a-vanilla-store-in-react)20 - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)21 - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)22 - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)23 - [Troubleshooting](#troubleshooting)23- - TBD24 25-## Reference25+### Signature26 27-### `useStoreWithEqualityFn` Signature28-27 ```ts30-useStoreWithEqualityFn<T, U = T>(storeApi: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U28+useStoreWithEqualityFn<T, U = T>(store: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U29 ```30 31+## Reference32+33+### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`34+35 #### Parameters36 37 - `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.24 unmodified lines63 type PositionStore = PositionStoreState & PositionStoreActions64 65 const positionStore = createStore<PositionStore>()((set) => ({66 position: { x: 0, y: 0 },65- setPosition: (position) => {66- set({ position })67- },67+ setPosition: (position) => set({ position }),68 }))69 ```70 71 Next, we'll create a `MovingDot` component that renders a div representing the dot. This component67 unmodified lines139 type PositionStore = PositionStoreState & PositionStoreActions140 141 const positionStore = createStore<PositionStore>()((set) => ({142 position: { x: 0, y: 0 },143- setPosition: (position) => {144- set({ position })145- },143+ setPosition: (position) => set({ position }),144 }))145 146 function MovingDot() {147 const position = useStoreWithEqualityFn(291 unmodified lines439 440 const createPositionStore = () => {441 return createStore<PositionStore>()((set) => ({442 position: { x: 0, y: 0 },445- setPosition: (position) => {446- set({ position })447- },443+ setPosition: (position) => set({ position }),444 }))445 }446 ```447 111 unmodified lines559 560 const createPositionStore = () => {561 return createStore<PositionStore>()((set) => ({562 position: { x: 0, y: 0 },567- setPosition: (position) => {568- set({ position })569- },563+ setPosition: (position) => set({ position }),564 }))565 }566 567 const PositionStoreContext = createContext<ReturnType<389 unmodified linesmodified:docs/hooks/use-store.md+14 added-18 removed
5 unmodified lines6 7 `useStore` is a React Hook that lets you use a vanilla store in React.8 9 ```js10-useStore(storeApi, selectorFn)10+const someState = useStore(store, selectorFn)11 ```12 13+- [Types](#types)14+ - [Signature](#signature)15 - [Reference](#reference)14- - [Signature](#usestore-signature)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)21- - TBD22 23-## Reference23+## Types24 25-### `useStore` Signature25+### Signature26 27 ```ts28-useStore<StoreApi<T>, U = T>(storeApi: StoreApi<T>, selectorFn?: (state: T) => U) => UseBoundStore<StoreApi<T>>28+useStore<StoreApi<T>, U = T>(store: StoreApi<T>, selectorFn?: (state: T) => U) => UseBoundStore<StoreApi<T>>29 ```30 31+## Reference32+33+### `useStore(store, selectorFn)`34+35 #### Parameters36 37 - `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.20 unmodified lines59 type PositionStore = PositionStoreState & PositionStoreActions60 61 const positionStore = createStore<PositionStore>()((set) => ({62 position: { x: 0, y: 0 },59- setPosition: (position) => {60- set({ position })61- },63+ setPosition: (position) => set({ position }),64 }))65 ```66 67 Next, we'll create a `MovingDot` component that renders a div representing the dot. This component57 unmodified lines125 type PositionStore = PositionStoreState & PositionStoreActions126 127 const positionStore = createStore<PositionStore>()((set) => ({128 position: { x: 0, y: 0 },127- setPosition: (position) => {128- set({ position })129- },129+ setPosition: (position) => set({ position }),130 }))131 132 function MovingDot() {133 const position = useStore(positionStore, (state) => state.position)275 unmodified lines409 410 const createPositionStore = () => {411 return createStore<PositionStore>()((set) => ({412 position: { x: 0, y: 0 },413- setPosition: (position) => {414- set({ position })415- },413+ setPosition: (position) => set({ position }),414 }))415 }416 ```417 109 unmodified lines527 528 const createPositionStore = () => {529 return createStore<PositionStore>()((set) => ({530 position: { x: 0, y: 0 },533- setPosition: (position) => {534- set({ position })535- },531+ setPosition: (position) => set({ position }),532 }))533 }534 535 const PositionStoreContext = createContext<ReturnType<387 unmodified linesadded:docs/middlewares/combine.md+103 added
1+---2+title: combine3+description: How to create a store and get types automatically inferred4+nav: 2015+---6+7+# combine8+9+`combine` middleware lets you create a cohesive state by merging an initial state with a state10+creator function that adds new state slices and actions. This is really helpful as it automatically11+infers types, so there’s no need for explicit type definitions.12+13+> [!TIP]14+> This makes state management more straightforward and efficient by making curried version of15+> `create` and `createStore` not necessary for middleware usage.16+17+```js18+const nextStateCreatorFn = combine(initialState, additionalStateCreatorFn)19+```20+21+- [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)27+28+## Types29+30+### Signature31+32+```ts33+combine<T, U>(initialState: T, additionalStateCreatorFn: StateCreator<T, [], [], U>): StateCreator<Omit<T, keyof U> & U, [], []>34+```35+36+## Reference37+38+### `combine(initialState, additionalStateCreatorFn)`39+40+#### Parameters41+42+- `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.46+47+#### Returns48+49+`combine` returns a state creator function.50+51+## Usage52+53+### Creating a store with inferred types54+55+This example shows you how you can create a store and get types automatically inferred, so you56+don’t need to define them explicitly.57+58+```ts59+import { createStore } from 'zustand/vanilla'60+import { combine } from 'zustand/middleware/combine'61+62+const positionStore = createStore(63+ combine({ position: { x: 0, y: 0 } }, (set) => ({64+ setPosition: (position) => set({ position }),65+ })),66+)67+68+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement69+const $dot = document.getElementById('dot') as HTMLDivElement70+71+$dotContainer.addEventListener('pointermove', (event) => {72+ positionStore.getState().setPosition({73+ x: event.clientX,74+ y: event.clientY,75+ })76+})77+78+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {79+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`80+}81+82+render(positionStore.getInitialState(), positionStore.getInitialState())83+84+positionStore.subscribe(render)85+```86+87+Here's the `html` code88+89+```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+```100+101+## Troubleshooting102+103+TBDadded:docs/middlewares/devtools.md+266 added
1+---2+title: devtools3+description: How to time-travel debug your store4+nav: 2055+---6+7+# devtools8+9+`devtools` middleware lets you use [Redux DevTools Extension](https://github.com/zalmoxisus/redux-devtools-extension)10+without 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).11+12+```js13+const nextStateCreatorFn = devtools(stateCreatorFn, devtoolsOptions)14+```15+16+- [Types](#types)17+ - [Signature](#signature)18+ - [Mutator](#mutator)19+- [Reference](#reference)20+- [Usage](#usage)21+ - [Debugging a store](#debugging-a-store)22+ - [Debugging a Slices pattern based store](#debugging-a-slices-pattern-based-store)23+- [Troubleshooting](#troubleshooting)24+ - [Only one store is displayed](#only-one-store-is-displayed)25+ - [Action names are labeled as 'anonymous'](#all-action-names-are-labeled-as-anonymous)26+27+## Types28+29+### Signature30+31+```ts32+devtools<T>(stateCreatorFn: StateCreator<T, [], []>, devtoolsOptions?: DevtoolsOptions): StateCreator<T, [['zustand/devtools', never]], []>33+```34+35+### Mutator36+37+<!-- prettier-ignore-start -->38+```ts39+['zustand/devtools', never]40+```41+<!-- prettier-ignore-end -->42+43+## Reference44+45+### `devtools(stateCreatorFn, devtoolsOptions)`46+47+#### Parameters48+49+- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.50+ Usually, you will return an object with the methods you want to expose.51+- **optional** `devtoolsOptions`: An object to define `Redux Devtools` options.52+ - **optional** `name`: A custom identifier for the connection in the Redux DevTools.53+ - **optional** `enabled`: Defaults to `true` when is on development mode, and defaults to `false`54+ when is on production mode. Enables or disables the Redux DevTools integration55+ for this store.56+ - **optional** `anonymousActionType`: Defaults to `anonymous`. A string to use as the action type57+ for anonymous mutations in the Redux DevTools.58+ - **optional** `store`: A custom identifier for the store in the Redux DevTools.59+60+#### Returns61+62+`devtools` returns a state creator function.63+64+## Usage65+66+### Debugging a store67+68+This example shows you how you can use `Redux Devtools` to debug a store69+70+```ts71+import { create, StateCreator } from 'zustand'72+73+type JungleStore = {74+ bears: number75+ addBear: () => void76+ fishes: number77+ addFish: () => void78+}79+80+const useJungleStore = create<JungleStore>()(81+ devtools((...args) => ({82+ bears: 0,83+ addBear: () =>84+ set((state) => ({ bears: state.bears + 1 }), undefined, 'jungle/addBear'),85+ fishes: 0,86+ addFish: () =>87+ set(88+ (state) => ({ fishes: state.fishes + 1 }),89+ undefined,90+ 'jungle/addFish',91+ ),92+ })),93+)94+```95+96+### Debugging a Slices pattern based store97+98+This example shows you how you can use `Redux Devtools` to debug a Slices pattern based store99+100+```ts101+import { create, StateCreator } from 'zustand'102+import { devtools } from 'zustand/middleware/devtools'103+104+type BearSlice = {105+ bears: number106+ addBear: () => void107+}108+109+type FishSlice = {110+ fishes: number111+ addFish: () => void112+}113+114+type JungleStore = BearSlice & FishSlice115+116+const createBearSlice: StateCreator<117+ JungleStore,118+ [['zustand/devtools', never]],119+ [],120+ BearSlice121+> = (set) => ({122+ bears: 0,123+ addBear: () =>124+ set(125+ (state) => ({ bears: state.bears + 1 }),126+ undefined,127+ 'jungle:bear/addBear',128+ ),129+})130+131+const createFishSlice: StateCreator<132+ JungleStore,133+ [['zustand/devtools', never]],134+ [],135+ FishSlice136+> = (set) => ({137+ fishes: 0,138+ addFish: () =>139+ set(140+ (state) => ({ fishes: state.fishes + 1 }),141+ undefined,142+ 'jungle:fish/addFish',143+ ),144+})145+146+const useJungleStore = create<JungleStore>()(147+ devtools((...args) => ({148+ ...createBearSlice(...args),149+ ...createFishSlice(...args),150+ })),151+)152+```153+154+## Troubleshooting155+156+### Only one store is displayed157+158+By default, `Redux Devtools` only show one store at a time, so in order to see other stores you159+need to use store selector and choose a different store.160+161+### All action names are labeled as 'anonymous'162+163+If an action type name is not provided, it is defaulted to "anonymous". You can customize this164+default value by providing a `anonymousActionType` parameter:165+166+For instance the next example doesn't have action type name:167+168+```ts169+import { create, StateCreator } from 'zustand'170+import { devtools } from 'zustand/middleware/devtools'171+172+type BearSlice = {173+ bears: number174+ addBear: () => void175+}176+177+type FishSlice = {178+ fishes: number179+ addFish: () => void180+}181+182+type JungleStore = BearSlice & FishSlice183+184+const createBearSlice: StateCreator<185+ JungleStore,186+ [['zustand/devtools', never]],187+ [],188+ BearSlice189+> = (set) => ({190+ bears: 0,191+ addBear: () => set((state) => ({ bears: state.bears + 1 })),192+ eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),193+})194+195+const createFishSlice: StateCreator<196+ JungleStore,197+ [['zustand/devtools', never]],198+ [],199+ FishSlice200+> = (set) => ({201+ fishes: 0,202+ addFish: () => set((state) => ({ fishes: state.fishes + 1 })),203+})204+205+const useJungleStore = create<JungleStore>()(206+ devtools((...args) => ({207+ ...createBearSlice(...args),208+ ...createFishSlice(...args),209+ })),210+)211+```212+213+In order to fix the previous example, we need to provide an action type name as the third parameter.214+Additionally, to preserve the default behavior of the replacement logic, the second parameter215+should be set to `undefined`.216+217+Here's the fixed previous example218+219+```ts220+import { create, StateCreator } from 'zustand'221+222+type BearSlice = {223+ bears: number224+ addBear: () => void225+}226+227+type FishSlice = {228+ fishes: number229+ addFish: () => void230+}231+232+type JungleStore = BearSlice & FishSlice233+234+const createBearSlice: StateCreator<235+ JungleStore,236+ [['zustand/devtools', never]],237+ [],238+ BearSlice239+> = (set) => ({240+ bears: 0,241+ addBear: () =>242+ set((state) => ({ bears: state.bears + 1 }), undefined, 'bear/addBear'),243+})244+245+const createFishSlice: StateCreator<246+ JungleStore,247+ [['zustand/devtools', never]],248+ [],249+ FishSlice250+> = (set) => ({251+ fishes: 0,252+ addFish: () =>253+ set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fish/addFish'),254+})255+256+const useJungleStore = create<JungleStore>()(257+ devtools((...args) => ({258+ ...createBearSlice(...args),259+ ...createFishSlice(...args),260+ })),261+)262+```263+264+> [!IMPORTANT]265+> Do not set the second parameter to `true` or `false` unless you want to override the default266+> replacement logicadded:docs/middlewares/immer.md+232 added
1+---2+title: immer3+description: How to perform immutable updates in a store without boilerplate code4+nav: 2065+---6+7+# immer8+9+`immer` middleware lets you perform immutable updates.10+11+```js12+const nextStateCreatorFn = immer(stateCreatorFn)13+```14+15+- [Types](#types)16+ - [Signature](#signature)17+ - [Mutator](#mutator)18+- [Reference](#reference)19+- [Usage](#usage)20+- [Troubleshooting](#troubleshooting)21+22+## Types23+24+### Signature25+26+```ts27+immer<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/immer', never]], []>28+```29+30+### Mutator31+32+<!-- prettier-ignore-start -->33+```ts34+['zustand/immer', never]35+```36+<!-- prettier-ignore-end -->37+38+## Reference39+40+### `immer(stateCreatorFn)`41+42+#### Parameters43+44+- `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.46+47+#### Returns48+49+`immer` returns a state creator function.50+51+## Usage52+53+### Updating state without boilerplate code54+55+In the next example, we're going to update the `person` object. Since it's a nested object, we need56+to create a copy of the entire object before making the update.57+58+```ts59+import { createStore } from 'zustand/vanilla'60+61+type PersonStoreState = {62+ person: { firstName: string; lastName: string; email: string }63+}64+65+type PersonStoreActions = {66+ setPerson: (67+ nextPerson: (68+ person: PersonStoreState['person'],69+ ) => PersonStoreState['person'] | PersonStoreState['person'],70+ ) => void71+}72+73+type PersonStore = PersonStoreState & PersonStoreActions74+75+const personStore = createStore<PersonStore>()((set) => ({76+ person: {77+ firstName: 'Barbara',78+ lastName: 'Hepworth',79+ email: 'bhepworth@sculpture.com',80+ },81+ setPerson: (nextPerson) =>82+ set((state) => ({83+ person:84+ typeof nextPerson === 'function'85+ ? nextPerson(state.person)86+ : nextPerson,87+ })),88+}))89+90+const $firstNameInput = document.getElementById(91+ 'first-name',92+) as HTMLInputElement93+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement94+const $emailInput = document.getElementById('email') as HTMLInputElement95+const $result = document.getElementById('result') as HTMLDivElement96+97+function handleFirstNameChange(event: Event) {98+ personStore.getState().setPerson((person) => ({99+ ...person,100+ firstName: (event.target as any).value,101+ }))102+}103+104+function handleLastNameChange(event: Event) {105+ personStore.getState().setPerson((person) => ({106+ ...person,107+ lastName: (event.target as any).value,108+ }))109+}110+111+function handleEmailChange(event: Event) {112+ personStore.getState().setPerson((person) => ({113+ ...person,114+ email: (event.target as any).value,115+ }))116+}117+118+$firstNameInput.addEventListener('input', handleFirstNameChange)119+$lastNameInput.addEventListener('input', handleLastNameChange)120+$emailInput.addEventListener('input', handleEmailChange)121+122+const render: Parameters<typeof personStore.subscribe>[0] = (state) => {123+ $firstNameInput.value = state.person.firstName124+ $lastNameInput.value = state.person.lastName125+ $emailInput.value = state.person.email126+127+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`128+}129+130+render(personStore.getInitialState(), personStore.getInitialState())131+132+personStore.subscribe(render)133+```134+135+Here's the `html` code136+137+```html138+<label style="display: block">139+ First name:140+ <input id="first-name" />141+</label>142+<label style="display: block">143+ Last name:144+ <input id="last-name" />145+</label>146+<label style="display: block">147+ Email:148+ <input id="email" />149+</label>150+<p id="result"></p>151+```152+153+To avoid manually copying the entire object before making updates, we'll use the `immer`154+middleware.155+156+```ts157+import { createStore } from 'zustand/vanilla'158+import { immer } from 'zustand/middleware/immer'159+160+type PersonStoreState = {161+ person: { firstName: string; lastName: string; email: string }162+}163+164+type PersonStoreActions = {165+ setPerson: (166+ nextPerson: (167+ person: PersonStoreState['person'],168+ ) => PersonStoreState['person'] | PersonStoreState['person'],169+ ) => void170+}171+172+type PersonStore = PersonStoreState & PersonStoreActions173+174+const personStore = createStore<PersonStore>()(175+ immer((set) => ({176+ person: {177+ firstName: 'Barbara',178+ lastName: 'Hepworth',179+ email: 'bhepworth@sculpture.com',180+ },181+ setPerson: (nextPerson) =>182+ set((state) => {183+ state.person = typeof nextPerson ? nextPerson(state.person) : nextPerson184+ }),185+ })),186+)187+188+const $firstNameInput = document.getElementById(189+ 'first-name',190+) as HTMLInputElement191+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement192+const $emailInput = document.getElementById('email') as HTMLInputElement193+const $result = document.getElementById('result') as HTMLDivElement194+195+function handleFirstNameChange(event: Event) {196+ personStore.getState().setPerson((person) => {197+ person.firstName = (event.target as any).value198+ })199+}200+201+function handleLastNameChange(event: Event) {202+ personStore.getState().setPerson((person) => {203+ person.lastName = (event.target as any).value204+ })205+}206+207+function handleEmailChange(event: Event) {208+ personStore.getState().setPerson((person) => {209+ person.email = (event.target as any).value210+ })211+}212+213+$firstNameInput.addEventListener('input', handleFirstNameChange)214+$lastNameInput.addEventListener('input', handleLastNameChange)215+$emailInput.addEventListener('input', handleEmailChange)216+217+const render: Parameters<typeof personStore.subscribe>[0] = (state) => {218+ $firstNameInput.value = state.person.firstName219+ $lastNameInput.value = state.person.lastName220+ $emailInput.value = state.person.email221+222+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`223+}224+225+render(personStore.getInitialState(), personStore.getInitialState())226+227+personStore.subscribe(render)228+```229+230+## Troubleshooting231+232+TBDadded:docs/middlewares/persist.md+988 added
1+---2+title: persist3+description: How to persist a store4+nav: 2075+---6+7+# persist8+9+`persist` middleware lets you persist a store's state across page reloads or application10+restarts.11+12+```js13+const nextStateCreatorFn = persist(stateCreatorFn, persistOptions)14+```15+16+- [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)28+29+## Types30+31+### Signature32+33+```ts34+persist<T, U>(stateCreatorFn: StateCreator<T, [], []>, persistOptions?: PersistOptions<T, U>): StateCreator<T, [['zustand/persist', U]], []>35+```36+37+### Mutator38+39+<!-- prettier-ignore-start -->40+```ts41+['zustand/persist', U]42+```43+<!-- prettier-ignore-end -->44+45+## Reference46+47+### `persist(stateCreatorFn)`48+49+#### Parameters50+51+- `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.67+68+#### Returns69+70+`persist` returns a state creator function.71+72+## Usage73+74+### Persisting a state75+76+In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`77+middleware. The example tracks the `position` of the mouse as it moves within a container and78+stores the `position` in local storage, so it persists even when the page reloads.79+80+We start by setting up a vanilla store that holds the position (an object with `x` and `y`81+coordinates) and an action to update it. We'll also use the `persist` middleware to store the82+position in `localStorage`.83+84+```ts85+import { createStore } from 'zustand/vanilla'86+import { persist } from 'zustand/middleware'87+88+type PositionStoreState = { position: { x: number; y: number } }89+90+type PositionStoreActions = {91+ setPosition: (nextPosition: PositionStoreState['position']) => void92+}93+94+type PositionStore = PositionStoreState & PositionStoreActions95+96+const 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+```106+107+Next, we'll track the mouse movements inside a div and update the store with the new position.108+109+```ts110+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement111+const $dot = document.getElementById('dot') as HTMLDivElement112+113+$dotContainer.addEventListener('pointermove', (event) => {114+ positionStore.getState().setPosition({115+ x: event.clientX,116+ y: event.clientY,117+ })118+})119+```120+121+We want to reflect the position updates on the screen by moving a div element122+(representing the dot) to the new coordinates.123+124+```ts125+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {126+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`127+}128+129+render(positionStore.getState(), positionStore.getState())130+131+positionStore.subscribe(render)132+```133+134+Here’s the complete code.135+136+```ts137+import { createStore } from 'zustand/vanilla'138+import { persist } from 'zustand/middleware'139+140+type PositionStoreState = { position: { x: number; y: number } }141+142+type PositionStoreActions = {143+ setPosition: (nextPosition: PositionStoreState['position']) => void144+}145+146+type PositionStore = PositionStoreState & PositionStoreActions147+148+const 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+)157+158+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement159+const $dot = document.getElementById('dot') as HTMLDivElement160+161+$dotContainer.addEventListener('pointermove', (event) => {162+ positionStore.getState().setPosition({163+ x: event.clientX,164+ y: event.clientY,165+ })166+})167+168+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {169+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`170+}171+172+render(positionStore.getState(), positionStore.getState())173+174+positionStore.subscribe(render)175+```176+177+Here's the `html` code178+179+```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+```190+191+### Persisting a state partially192+193+In this tutorial, we'll create a simple position tracker using vanilla store and the `persist`194+middleware. 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`.197+198+We’ll first create a vanilla store that holds the position state and actions to update it. We'll199+use the `persist` middleware to persist only the relevant part of the state (in this case, the200+context containing the position).201+202+```ts203+import { createStore } from 'zustand/vanilla'204+import { persist } from 'zustand/middleware'205+206+type PositionStoreState = {207+ context: {208+ position: { x: number; y: number }209+ }210+}211+212+type PositionStoreActions = {213+ actions: {214+ setPosition: (215+ nextPosition: PositionStoreState['context']['position'],216+ ) => void217+ }218+}219+220+type PositionStore = PositionStoreState & PositionStoreActions221+222+const 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+```239+240+Next, we'll track the mouse movements inside a div and update the store with the new position.241+242+```ts243+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement244+const $dot = document.getElementById('dot') as HTMLDivElement245+246+$dotContainer.addEventListener('pointermove', (event) => {247+ positionStore.getState().actions.setPosition({248+ x: event.clientX,249+ y: event.clientY,250+ })251+})252+```253+254+We want to reflect the position updates on the screen by moving a div element255+(representing the dot) to the new coordinates.256+257+```ts258+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {259+ $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`260+}261+262+render(positionStore.getState(), positionStore.getState())263+264+positionStore.subscribe(render)265+```266+267+Here’s the full code to create a dot that follows your mouse movement inside a container and268+persists the `context` in `localStorage`.269+270+```ts271+import { createStore } from 'zustand/vanilla'272+import { persist } from 'zustand/middleware'273+274+type PositionStoreState = {275+ context: {276+ position: { x: number; y: number }277+ }278+}279+280+type PositionStoreActions = {281+ actions: {282+ setPosition: (283+ nextPosition: PositionStoreState['context']['position'],284+ ) => void285+ }286+}287+288+type PositionStore = PositionStoreState & PositionStoreActions289+290+const 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+)306+307+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement308+const $dot = document.getElementById('dot') as HTMLDivElement309+310+$dotContainer.addEventListener('pointermove', (event) => {311+ positionStore.getState().actions.setPosition({312+ x: event.clientX,313+ y: event.clientY,314+ })315+})316+317+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {318+ $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`319+}320+321+render(positionStore.getState(), positionStore.getState())322+323+positionStore.subscribe(render)324+```325+326+Here's the `html` code327+328+```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+```339+340+### Persisting a state with custom storage341+342+In this mini tutorial, we’ll create a simple position-tracking system using vanilla store, where343+the position state is persisted in the URL's search parameters. This approach allows state344+persistence directly in the browser's URL, which can be useful for maintaining state across page345+reloads or sharing links with state embedded.346+347+We need to implement functions to manipulate URL search parameters as if they were a storage348+mechanism. This includes retrieving, setting, and removing parameters.349+350+```ts351+const getSearchParams = () => {352+ return new URL(location.href).searchParams353+}354+355+const updateSearchParams = (searchParams: URLSearchParams) => {356+ window.history.replaceState(357+ {},358+ '',359+ `${location.pathname}?${searchParams.toString()}`,360+ )361+}362+363+const getSearchParam = (key: string) => {364+ const searchParams = getSearchParams()365+ return searchParams.get(key)366+}367+368+const updateSearchParam = (key: string, value: string) => {369+ const searchParams = getSearchParams()370+ searchParams.set(key, value)371+372+ updateSearchParams(searchParams)373+}374+375+const removeSearchParam = (key: string) => {376+ const searchParams = getSearchParams()377+ searchParams.delete(key)378+379+ updateSearchParams(searchParams)380+}381+```382+383+To 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 that385+manipulate search parameters.386+387+```ts388+const searchParamsStorage = {389+ getItem: (key: string) => getSearchParam(key),390+ setItem: (key: string, value: string) => updateSearchParam(key, value),391+ removeItem: (key: string) => removeSearchParam(key),392+}393+```394+395+Now, we initialize the vanilla store using the `persist` middleware, specifying that we want to use396+our custom storage. Instead of the default `localStorage` or `sessionStorage`, we’ll persist the397+position data in the URL search parameters.398+399+```ts400+import { createStore } from 'zustand/vanilla'401+import { persist, createJSONStorage } from 'zustand/middleware'402+403+type PositionStoreState = { position: { x: number; y: number } }404+405+type PositionStoreActions = {406+ setPosition: (nextPosition: PositionStoreState['position']) => void407+}408+409+type PositionStore = PositionStoreState & PositionStoreActions410+411+const 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+```424+425+Next, we'll track the mouse movements inside a div and update the store with the new position.426+427+```ts428+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement429+const $dot = document.getElementById('dot') as HTMLDivElement430+431+$dotContainer.addEventListener('pointermove', (event) => {432+ positionStore.getState().setPosition({433+ x: event.clientX,434+ y: event.clientY,435+ })436+})437+```438+439+We want to reflect the position updates on the screen by moving a div element440+(representing the dot) to the new coordinates.441+442+```ts443+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {444+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`445+}446+447+render(positionStore.getState(), positionStore.getState())448+449+positionStore.subscribe(render)450+```451+452+Here’s the full code to create a dot that follows your mouse movement inside a container and453+persists the position in URL's search parameters.454+455+```ts456+import { createStore } from 'zustand/vanilla'457+import { persist, createJSONStorage } from 'zustand/middleware'458+459+type PositionStoreState = { position: { x: number; y: number } }460+461+type PositionStoreActions = {462+ setPosition: (nextPosition: PositionStoreState['position']) => void463+}464+465+type PositionStore = PositionStoreState & PositionStoreActions466+467+const getSearchParams = () => {468+ return new URL(location.href).searchParams469+}470+471+const updateSearchParams = (searchParams: URLSearchParams) => {472+ window.history.replaceState(473+ {},474+ '',475+ `${location.pathname}?${searchParams.toString()}`,476+ )477+}478+479+const getSearchParam = (key: string) => {480+ const searchParams = getSearchParams()481+ return searchParams.get(key)482+}483+484+const updateSearchParam = (key: string, value: string) => {485+ const searchParams = getSearchParams()486+ searchParams.set(key, value)487+488+ updateSearchParams(searchParams)489+}490+491+const removeSearchParam = (key: string) => {492+ const searchParams = getSearchParams()493+ searchParams.delete(key)494+495+ updateSearchParams(searchParams)496+}497+498+const searchParamsStorage = {499+ getItem: (key: string) => getSearchParam(key),500+ setItem: (key: string, value: string) => updateSearchParam(key, value),501+ removeItem: (key: string) => removeSearchParam(key),502+}503+504+const 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+)516+517+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement518+const $dot = document.getElementById('dot') as HTMLDivElement519+520+$dotContainer.addEventListener('pointermove', (event) => {521+ positionStore.getState().setPosition({522+ x: event.clientX,523+ y: event.clientY,524+ })525+})526+527+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {528+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`529+}530+531+render(positionStore.getState(), positionStore.getState())532+533+positionStore.subscribe(render)534+```535+536+Here's the `html` code537+538+```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+```549+550+### Persisting a state through versioning and migrations551+552+In this tutorial, we’ll explore how to manage state persistence using versioning and migration.553+We will demonstrate how to evolve your state schema across versions without breaking existing554+persisted data.555+556+Before moving to versioned state management, we simulate an initial state for `version` 0. This is557+done 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.559+560+```ts561+// For tutorial purposes only562+if (!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+```572+573+Next, we use `persist` middleware to handle state persistence. We also add a migration function to574+handle 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.576+577+```ts578+migrate: (persisted: any, version) => {579+ if (version === 0) {580+ persisted.position = { x: persisted.x, y: persisted.y }581+ delete persisted.x582+ delete persisted.y583+ }584+585+ return persisted586+}587+```588+589+Next, we'll track the mouse movements inside a div and update the store with the new position.590+591+```ts592+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement593+const $dot = document.getElementById('dot') as HTMLDivElement594+595+$dotContainer.addEventListener('pointermove', (event) => {596+ positionStore.getState().setPosition({597+ x: event.clientX,598+ y: event.clientY,599+ })600+})601+```602+603+We want to reflect the position updates on the screen by moving a div element604+(representing the dot) to the new coordinates.605+606+```ts607+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {608+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`609+}610+611+render(positionStore.getState(), positionStore.getState())612+613+positionStore.subscribe(render)614+```615+616+Here’s the complete code.617+618+```ts619+import { createStore } from 'zustand/vanilla'620+import { persist } from 'zustand/middleware'621+622+// For tutorial purposes only623+if (!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+}632+633+type PositionStoreState = { position: { x: number; y: number } }634+635+type PositionStoreActions = {636+ setPosition: (nextPosition: PositionStoreState['position']) => void637+}638+639+type PositionStore = PositionStoreState & PositionStoreActions640+641+const 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+ }656+657+ return persisted658+ },659+ },660+ ),661+)662+663+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement664+const $dot = document.getElementById('dot') as HTMLDivElement665+666+$dotContainer.addEventListener('pointermove', (event) => {667+ positionStore.getState().setPosition({668+ x: event.clientX,669+ y: event.clientY,670+ })671+})672+673+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {674+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`675+}676+677+render(positionStore.getState(), positionStore.getState())678+679+positionStore.subscribe(render)680+```681+682+Here's the `html` code683+684+```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+```695+696+### Persisting a state with nested objects697+698+In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`699+and `y` coordinates. We will also implement persistence using `localStorage` and demonstrate how to700+handle merging of state with potentially missing fields.701+702+To 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.704+705+```ts706+if (!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+```716+717+Now, we will create the store and configure it to use persistence and deep merging.718+719+```ts720+import { createStore } from 'zustand/vanilla'721+import { persist } from 'zustand/middleware'722+import createDeepMerge from '@fastify/deepmerge'723+724+const deepMerge = createDeepMerge({ all: true })725+726+type PositionStoreState = { position: { x: number; y: number } }727+728+type PositionStoreActions = {729+ setPosition: (nextPosition: PositionStoreState['position']) => void730+}731+732+type PositionStore = PositionStoreState & PositionStoreActions733+734+const 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+```747+748+Next, we'll track the mouse movements inside a div and update the store with the new position.749+750+```ts751+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement752+const $dot = document.getElementById('dot') as HTMLDivElement753+754+$dotContainer.addEventListener('pointermove', (event) => {755+ positionStore.getState().setPosition({756+ x: event.clientX,757+ y: event.clientY,758+ })759+})760+```761+762+We want to reflect the position updates on the screen by moving a div element763+(representing the dot) to the new coordinates.764+765+```ts766+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {767+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`768+}769+770+render(positionStore.getState(), positionStore.getState())771+772+positionStore.subscribe(render)773+```774+775+Here’s the complete code.776+777+```ts778+import { createStore } from 'zustand/vanilla'779+import { persist } from 'zustand/middleware'780+import createDeepMerge from '@fastify/deepmerge'781+782+const deepMerge = createDeepMerge({ all: true })783+784+// For tutorial purposes only785+if (!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+}794+795+type PositionStoreState = { position: { x: number; y: number } }796+797+type PositionStoreActions = {798+ setPosition: (nextPosition: PositionStoreState['position']) => void799+}800+801+type PositionStore = PositionStoreState & PositionStoreActions802+803+const 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+)815+816+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement817+const $dot = document.getElementById('dot') as HTMLDivElement818+819+$dotContainer.addEventListener('pointermove', (event) => {820+ positionStore.getState().setPosition({821+ x: event.clientX,822+ y: event.clientY,823+ })824+})825+826+const 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+}830+831+render(positionStore.getState(), positionStore.getState())832+833+positionStore.subscribe(render)834+```835+836+Here's the `html` code837+838+```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+```849+850+### Persisting a state and hydrate it manually851+852+In this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`853+and `y` coordinates. We will also implement persistence using `localStorage` and explore how to854+skip the hydration process and manually trigger rehydration after a delay.855+856+We start by setting up a vanilla store that holds the position (an object with `x` and `y`857+coordinates) and an action to update it. Furthermore, we'll also use the `persist` middleware to858+store the position in `localStorage` but skipping hydration.859+860+```ts861+import { createStore } from 'zustand/vanilla'862+import { persist } from 'zustand/middleware'863+864+type PositionStoreState = { position: { x: number; y: number } }865+866+type PositionStoreActions = {867+ setPosition: (nextPosition: PositionStoreState['position']) => void868+}869+870+type PositionStore = PositionStoreState & PositionStoreActions871+872+const 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+```885+886+Since we skipped hydration in the initial setup, we will manually rehydrate the state. Here, we’re887+using `setTimeout` to simulate a delayed rehydration.888+889+```ts890+setTimeout(() => {891+ positionStore.persist.rehydrate()892+}, 2000)893+```894+895+Next, we'll track the mouse movements inside a div and update the store with the new position.896+897+```ts898+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement899+const $dot = document.getElementById('dot') as HTMLDivElement900+901+$dotContainer.addEventListener('pointermove', (event) => {902+ positionStore.getState().setPosition({903+ x: event.clientX,904+ y: event.clientY,905+ })906+})907+```908+909+We want to reflect the position updates on the screen by moving a div element910+(representing the dot) to the new coordinates.911+912+```ts913+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {914+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`915+}916+917+render(positionStore.getState(), positionStore.getState())918+919+positionStore.subscribe(render)920+```921+922+Here’s the complete code.923+924+```ts925+import { createStore } from 'zustand/vanilla'926+import { persist } from 'zustand/middleware'927+928+type PositionStoreState = { position: { x: number; y: number } }929+930+type PositionStoreActions = {931+ setPosition: (nextPosition: PositionStoreState['position']) => void932+}933+934+type PositionStore = PositionStoreState & PositionStoreActions935+936+const 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+)948+949+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement950+const $dot = document.getElementById('dot') as HTMLDivElement951+952+$dotContainer.addEventListener('pointermove', (event) => {953+ positionStore.getState().setPosition({954+ x: event.clientX,955+ y: event.clientY,956+ })957+})958+959+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {960+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`961+}962+963+setTimeout(() => {964+ positionStore.persist.rehydrate()965+}, 2000)966+967+render(positionStore.getState(), positionStore.getState())968+969+positionStore.subscribe(render)970+```971+972+Here's the `html` code973+974+```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+```985+986+## Troubleshooting987+988+TBDadded:docs/middlewares/redux.md+170 added
1+---2+title: redux3+description: How to use actions and reducers in a store4+nav: 2085+---6+7+# redux8+9+`redux` middleware lets you update a store through actions and reducers just like redux.10+11+```js12+const nextStateCreatorFn = redux(reducerFn, initialState)13+```14+15+- [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)22+23+## Types24+25+### Signature26+27+```ts28+redux<T, A>(reducerFn: (state: T, action: A) => T, initialState: T): StateCreator<T & { dispatch: (action: A) => A }, [['zustand/redux', A]], []>29+```30+31+### Mutator32+33+<!-- prettier-ignore-start -->34+```ts35+['zustand/redux', A]36+```37+<!-- prettier-ignore-end -->38+39+## Reference40+41+### `redux(reducerFn, initialState)`42+43+#### Parameters44+45+- `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.49+50+#### Returns51+52+`redux` returns a state creator function.53+54+## Usage55+56+### Updating state through actions and reducers57+58+```ts59+import { createStore } from 'zustand/vanilla'60+import { redux } from 'zustand/middleware/redux'61+62+type PersonStoreState = {63+ firstName: string64+ lastName: string65+ email: string66+}67+68+type PersonStoreAction =69+ | { type: 'person/setFirstName'; firstName: string }70+ | { type: 'person/setLastName'; lastName: string }71+ | { type: 'person/setEmail'; email: string }72+73+type PersonStore = PersonStoreState & PersonStoreActions74+75+const personStoreReducer = (76+ state: PersonStoreState,77+ action: PersonStoreAction,78+) => {79+ switch (action.type) {80+ case 'person/setFirstName': {81+ return { ...state, firstName: action.firstName }82+ }83+ case 'person/setLastName': {84+ return { ...state, lastName: action.lastName }85+ }86+ case 'person/setEmail': {87+ return { ...state, email: action.email }88+ }89+ default: {90+ return state91+ }92+ }93+}94+95+const personStoreInitialState: PersonStoreState = {96+ firstName: 'Barbara',97+ lastName: 'Hepworth',98+ email: 'bhepworth@sculpture.com',99+}100+101+const personStore = createStore<PersonStore>()(102+ redux(personStoreReducer, personStoreInitialState),103+)104+105+const $firstNameInput = document.getElementById(106+ 'first-name',107+) as HTMLInputElement108+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement109+const $emailInput = document.getElementById('email') as HTMLInputElement110+const $result = document.getElementById('result') as HTMLDivElement111+112+function handleFirstNameChange(event: Event) {113+ personStore.dispatch({114+ type: 'person/setFirstName',115+ firstName: (event.target as any).value,116+ })117+}118+119+function handleLastNameChange(event: Event) {120+ personStore.dispatch({121+ type: 'person/setLastName',122+ lastName: (event.target as any).value,123+ })124+}125+126+function handleEmailChange(event: Event) {127+ personStore.dispatch({128+ type: 'person/setEmail',129+ email: (event.target as any).value,130+ })131+}132+133+$firstNameInput.addEventListener('input', handleFirstNameChange)134+$lastNameInput.addEventListener('input', handleLastNameChange)135+$emailInput.addEventListener('input', handleEmailChange)136+137+const render: Parameters<typeof personStore.subscribe>[0] = (person) => {138+ $firstNameInput.value = person.firstName139+ $lastNameInput.value = person.lastName140+ $emailInput.value = person.email141+142+ $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`143+}144+145+render(personStore.getInitialState(), personStore.getInitialState())146+147+personStore.subscribe(render)148+```149+150+Here's the `html` code151+152+```html153+<label style="display: block">154+ First name:155+ <input id="first-name" />156+</label>157+<label style="display: block">158+ Last name:159+ <input id="last-name" />160+</label>161+<label style="display: block">162+ Email:163+ <input id="email" />164+</label>165+<p id="result"></p>166+```167+168+## Troubleshooting169+170+TBDadded:docs/middlewares/subscribe-with-selector.md+121 added
1+---2+title: subscribeWithSelector3+description: How to subscribe to granular store updates in a store4+nav: 2105+---6+7+# subscribeWithSelector8+9+`subscribeWithSelector` middleware lets you subscribe to specific data based on current state.10+11+```js12+const nextStateCreatorFn = subscribeWithSelector(stateCreatorFn)13+```14+15+- [Types](#types)16+ - [Signature](#signature)17+ - [Mutator](#mutator)18+- [Reference](#reference)19+- [Usage](#usage)20+- [Troubleshooting](#troubleshooting)21+22+## Types23+24+### Signature25+26+```ts27+subscribeWithSelector<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/subscribeWithSelector', never]], []>28+```29+30+### Mutator31+32+<!-- prettier-ignore-start -->33+```ts34+['zustand/subscribeWithSelector', never]35+```36+<!-- prettier-ignore-end -->37+38+## Reference39+40+### `subscribeWithSelector(stateCreatorFn)`41+42+#### Parameters43+44+- `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.46+47+#### Returns48+49+`subscribeWithSelector` returns a state creator function.50+51+## Usage52+53+### Subscribing partial state updates54+55+By subscribing to partial state updates, you register a callback that fires whenever the store's56+partial state updates. We can use `subscribe` for external state management.57+58+```ts59+import { createStore } from 'zustand/vanilla'60+import { subscribeWithSelector } from 'zustand/middleware/subscribeWithSelector'61+62+type PositionStoreState = { position: { x: number; y: number } }63+64+type PositionStoreActions = {65+ setPosition: (nextPosition: PositionStoreState['position']) => void66+}67+68+type PositionStore = PositionStoreState & PositionStoreActions69+70+const positionStore = createStore<PositionStore>()(71+ subscribeWithSelector((set) => ({72+ position: { x: 0, y: 0 },73+ setPosition: (position) => set({ position }),74+ })),75+)76+77+const $dot = document.getElementById('dot') as HTMLDivElement78+79+$dot.addEventListener('mouseenter', (event) => {80+ const parent = event.currentTarget.parentElement81+ const parentWidth = parent.clientWidth82+ const parentHeight = parent.clientHeight83+84+ positionStore.getState().setPosition({85+ x: Math.ceil(Math.random() * parentWidth),86+ y: Math.ceil(Math.random() * parentHeight),87+ })88+})89+90+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {91+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`92+}93+94+render(positionStore.getInitialState(), positionStore.getInitialState())95+96+positionStore.subscribe((state) => state.position, render)97+98+const logger: Parameters<typeof positionStore.subscribe>[0] = (x) => {99+ console.log('new x position', { x })100+}101+102+positionStore.subscribe((state) => state.position.x, logger)103+```104+105+Here's the `html` code106+107+```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+```118+119+## Troubleshooting120+121+TBD