Skip to content
Myr

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

13 files+2094 added−281 removed

modified:docs/apis/create-store.md+56 added-80 removed
5 unmodified lines
67`createStore` lets you create a vanilla store that exposes API utilities.89```js10createStore(stateCreatorFn)10const someStore = createStore(stateCreatorFn)11```1213- [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)2425## Reference25## Types2627### `createStore` Signature27### Signature2829```ts30createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>31```3233## Reference3435### `createStore(stateCreatorFn)`3637#### Parameters3835- `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.4142#### Returns43
3 unmodified lines
47## Usage4849### Updating state based on previous state5047This example shows how you can support **updater functions** for your **actions**.51This example shows how you can support **updater functions** within **actions**.5253```tsx54import { createStore } from 'zustand/vanilla'55
10 unmodified lines
66type AgeStore = AgeStoreState & AgeStoreActions6768const 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}))7576function increment() {77 ageStore.getState().setAge((currentAge) => currentAge + 1)
59 unmodified lines
137$dotContainer.addEventListener('pointermove', (event) => {138 xStore.setState(event.clientX, true)139})140138const render: Parameters<typeof xStore.subscribe>[0] = (state) => {139 const position = { y: 0, x: state }140141 $dot.style.transform = `translate(${position.x}px, ${position.y}px)`141const render: Parameters<typeof xStore.subscribe>[0] = (x) => {142 $dot.style.transform = `translate(${x}px, 0)`143}144145render(xStore.getInitialState(), xStore.getInitialState())146
27 unmodified lines
174175```ts176import { createStore } from 'zustand/vanilla'177177type PositionStoreState = { x: number; y: number }178type PositionStoreState = { position: { x: number; y: number } }179180type PositionStoreActions = {180 setPosition: (nextPosition: Partial<PositionStoreState>) => void181 setPosition: (nextPosition: PositionStoreState['position']) => void182}183184type PositionStore = PositionStoreState & PositionStoreActions185186const 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}))190191const $dotContainer = document.getElementById('dot-container') as HTMLDivElement192const $dot = document.getElementById('dot') as HTMLDivElement
5 unmodified lines
198 })199})200201const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {204 const position = { x: state.x, y: state.y }205206 $dot.style.transform = `translate(${position.x}px, ${position.y}px)`202 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`203}204205render(positionStore.getInitialState(), positionStore.getInitialState())206
43 unmodified lines
250$dotContainer.addEventListener('pointermove', (event) => {251 positionStore.setState([event.clientX, event.clientY], true)252})253258const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {259 const position = { x: state[0], y: state[1] }260261 $dot.style.transform = `translate(${position.x}px, ${position.y}px)`254const render: Parameters<typeof positionStore.subscribe>[0] = ([x, y]) => {255 $dot.style.transform = `translate(${x}px, ${y}px)`256}257258render(positionStore.getInitialState(), positionStore.getInitialState())259
21 unmodified lines
281282```ts283import { createStore } from 'zustand/vanilla'284291type PositionStoreState = { x: number; y: number }285type PositionStoreState = { position: { x: number; y: number } }286287type PositionStoreActions = {294 setPosition: (nextPosition: Partial<PositionStoreState>) => void288 setPosition: (nextPosition: PositionStoreState['position']) => void289}290291type PositionStore = PositionStoreState & PositionStoreActions292293const 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}))297298const $dot = document.getElementById('dot') as HTMLDivElement299
8 unmodified lines
308 })309})310311const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {321 const position = { x: state.x, y: state.y }322323 $dot.style.transform = `translate(${position.x}px, ${position.y}px)`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) => {331 console.log('new position', { position: { x: state.x, y: state.x } })320 console.log('new position', { position: state.position })321}322323positionStore.subscribe(logger)324```
26 unmodified lines
351```ts352import { createStore } from 'zustand/vanilla'353354type PersonStoreState = {366 firstName: string367 lastName: string368 email: string355 person: { firstName: string; lastName: string; email: string }356}357358type PersonStoreActions = {372 setPerson: (nextPerson: Partial<PersonStoreState>) => void359 setPerson: (nextPerson: PersonStoreState['person']) => void360}361362type PersonStore = PersonStoreState & PersonStoreActions363364const 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}))372373const $firstNameInput = document.getElementById(374 'first-name',
2 unmodified lines
377const $emailInput = document.getElementById('email') as HTMLInputElement378const $result = document.getElementById('result') as HTMLDivElement379380function handleFirstNameChange(event: Event) {394 personStore.getState().firstName = (event.target as any).value381 personStore.getState().person.firstName = (event.target as any).value382}383384function handleLastNameChange(event: Event) {398 personStore.getState().lastName = (event.target as any).value385 personStore.getState().person.lastName = (event.target as any).value386}387388function handleEmailChange(event: Event) {402 personStore.getState().email = (event.target as any).value389 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) => {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.email400416 $firstNameInput.value = person.firstName417 $lastNameInput.value = person.lastName418 $emailInput.value = person.email419420 $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`401 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`402}403404render(personStore.getInitialState(), personStore.getInitialState())405
46 unmodified lines
452```ts {32-34,38-40,44-46}453import { createStore } from 'zustand/vanilla'454455type PersonStoreState = {475 firstName: string476 lastName: string477 email: string456 person: { firstName: string; lastName: string; email: string }457}458459type PersonStoreActions = {481 setPerson: (nextPerson: Partial<PersonStoreState>) => void460 setPerson: (nextPerson: PersonStoreState['person']) => void461}462463type PersonStore = PersonStoreState & PersonStoreActions464465const 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}))473474const $firstNameInput = document.getElementById(475 'first-name',
3 unmodified lines
479const $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}501
1 unmodified line
503$lastNameInput.addEventListener('input', handleLastNameChange)504$emailInput.addEventListener('input', handleEmailChange)505506const 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.email510531 $firstNameInput.value = person.firstName532 $lastNameInput.value = person.lastName533 $emailInput.value = person.email534535 $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`511 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`512}513514render(personStore.getInitialState(), personStore.getInitialState())515
2 unmodified lines
modified:docs/apis/create-with-equality-fn.md+63 added-82 removed
7 unmodified lines
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```js12createWithEqualityFn(stateCreatorFn, equalityFn)12const useSomeStore = createWithEqualityFn(stateCreatorFn, equalityFn)13```1415- [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 lines
24 - [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)2727## Reference28## Types2929### `createWithEqualityFn` Signature30### Signature3132```ts33createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, equalityFn?: (a: T, b: T) => boolean): UseBoundStore<StoreApi<T>>34```3536## Reference3738### `createWithEqualityFn(stateCreatorFn)`3940#### Parameters4137- `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.4546#### Returns
2 unmodified lines
49lets you return data that is based on current state, using a selector function, and lets you skip50re-renders using an equality function. It should take a selector function, and an equality function51as arguments.5253## Usage5455### Updating state based on previous state5657To update a state based on previous state we should use **updater functions**. Read more58about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).5953This example shows how you can support **updater functions** for your **actions**.60This example shows how you can support **updater functions** within **actions**.6162```tsx63import { createWithEqualityFn } from 'zustand/traditional'64import { shallow } from 'zustand/vanilla/shallow'
12 unmodified lines
7778const 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 lines
187```tsx188import { createWithEqualityFn } from 'zustand/traditional'189import { shallow } from 'zustand/vanilla/shallow'190185type PositionStoreState = { x: number; y: number }191type PositionStoreState = { position: { x: number; y: number } }192193type PositionStoreActions = {188 setPosition: (nextPosition: Partial<PositionStoreState>) => void194 setPosition: (nextPosition: PositionStoreState['position']) => void195}196197type PositionStore = PositionStoreState & PositionStoreActions198199const 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)206207export 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)210211 return (212 <div213 onPointerMove={(e) => {
53 unmodified lines
267)268269export 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 }275276 return (277 <div278 onPointerMove={(e) => {
91 unmodified lines
370import { useEffect } from 'react'371import { createWithEqualityFn } from 'zustand/traditional'372import { shallow } from 'zustand/vanilla/shallow'373373type PositionStoreState = { x: number; y: number }374type PositionStoreState = { position: { x: number; y: number } }375376type PositionStoreActions = {376 setPosition: (nextPosition: Partial<PositionStoreState>) => void377 setPosition: (nextPosition: PositionStoreState['position']) => void378}379380type PositionStore = PositionStoreState & PositionStoreActions381382const 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)389390export 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)393394 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 )400401 return () => {402 unsubscribePositionStore()403 }
49 unmodified lines
453import { createWithEqualityFn } from 'zustand/traditional'454import { shallow } from 'zustand/vanilla/shallow'455456type PersonStoreState = {459 firstName: string460 lastName: string461 email: string457 person: { firstName: string; lastName: string; email: string }458}459460type PersonStoreActions = {465 setPerson: (nextPerson: Partial<PersonStoreState>) => void461 setPerson: (nextPerson: PersonStoreState['person']) => void462}463464type PersonStore = PersonStoreState & PersonStoreActions465466const 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)477478export 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)481492 function handleFirstNameChange(e) {482 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {483 person.firstName = e.target.value484 }485496 function handleLastNameChange(e) {486 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {487 person.lastName = e.target.value488 }489500 function handleEmailChange(e) {490 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {491 person.email = e.target.value492 }493494 return (
28 unmodified lines
523`setPerson`. But here you want to also copy the existing data into it because only one of the524fields has changed:525526```ts537setPerson({538 firstName: e.target.value, // New first name from the input539})527setPerson({ ...person, firstName: e.target.value }) // New first name from the input528```529530> [!NOTE]531> We don’t need to copy every property separately due to `set` function performing shallow merge by
3 unmodified lines
535536Notice how you didn’t declare a separate state variable for each input field. For large forms,537keeping all data grouped in an object is very convenient—as long as you update it correctly!538551```tsx {39,43,47}539```tsx {32,36,40}540import { type ChangeEvent } from 'react'541import { createWithEqualityFn } from 'zustand/traditional'542import { shallow } from 'zustand/vanilla/shallow'543544type PersonStoreState = {556 firstName: string557 lastName: string558 email: string545 person: { firstName: string; lastName: string; email: string }546}547548type PersonStoreActions = {562 setPerson: (nextPerson: Partial<PersonStoreState>) => void549 setPerson: (nextPerson: PersonStoreState['person']) => void550}551552type PersonStore = PersonStoreState & PersonStoreActions553554const 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)565566export 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)569589 function handleFirstNameChange(e) {590 setPerson({ firstName: e.target.value })570 function handleFirstNameChange(e: ChangeEvent<HTLMInputElement>) {571 setPerson({ ...person, firstName: e.target.value })572 }573593 function handleLastNameChange(e) {594 setPerson({ lastName: e.target.value })574 function handleLastNameChange(e: ChangeEvent<HTLMInputElement>) {575 setPerson({ ...person, lastName: e.target.value })576 }577597 function handleEmailChange(e) {598 setPerson({ email: e.target.value })578 function handleEmailChange(e: ChangeEvent<HTLMInputElement>) {579 setPerson({ ...person, email: e.target.value })580 }581582 return (583 <>
19 unmodified lines
modified:docs/apis/create.md+51 added-72 removed
5 unmodified lines
67`create` lets you create a React Hook with API utilities attached.89```js10create(stateCreatorFn)10const useSomeStore = create(stateCreatorFn)11```1213- [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 lines
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)2525## Reference26## Types2727### `create` Signature28### Signature2930```ts31create<T>()(stateCreatorFn: StateCreator<T, [], []>): UseBoundStore<StoreApi<T>>32```3334## Reference3536### `create(stateCreatorFn)`3738#### Parameters3935- `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.4243#### Returns44
7 unmodified lines
5253To 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).5551This example shows how you can support **updater functions** for your **actions**.56This example shows how you can support **updater functions** within **actions**.5758```tsx59import { create } from 'zustand'60
115 unmodified lines
176177```tsx178import { create } from 'zustand'179175type PositionStoreState = { x: number; y: number }180type PositionStoreState = { position: { x: number; y: number } }181182type PositionStoreActions = {178 setPosition: (nextPosition: Partial<PositionStoreState>) => void183 setPosition: (nextPosition: PositionStoreState['position']) => void184}185186type PositionStore = PositionStoreState & PositionStoreActions187188const 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}))192193export 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)196197 return (198 <div199 onPointerMove={(e) => {
150 unmodified lines
350```tsx351import { useEffect } from 'react'352import { create } from 'zustand'353354type PositionStoreState = { x: number; y: number }354type PositionStoreState = { position: { x: number; y: number } }355356type PositionStoreActions = {357 setPosition: (nextPosition: Partial<PositionStoreState>) => void357 setPosition: (nextPosition: PositionStoreState['position']) => void358}359360type PositionStore = PositionStoreState & PositionStoreActions361362const 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}))366367export 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)370371 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 )377378 return () => {379 unsubscribePositionStore()380 }
63 unmodified lines
444const 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}))450451export 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)454466 function handleFirstNameChange(e) {455 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {456 person.firstName = e.target.value457 }458470 function handleLastNameChange(e) {459 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {460 person.lastName = e.target.value461 }462474 function handleEmailChange(e) {463 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {464 person.email = e.target.value465 }466467 return (
28 unmodified lines
496`setPerson`. But here you want to also copy the existing data into it because only one of the497fields has changed:498499```ts511setPerson({512 firstName: e.target.value, // New first name from the input513})500setPerson({ ...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 by
3 unmodified lines
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!511525```tsx {35,39,43}512```tsx {27,31,35}513import { create } from 'zustand'514515type PersonStoreState = {529 firstName: string530 lastName: string531 email: string516 person: { firstName: string; lastName: string; email: string }517}518519type PersonStoreActions = {535 setPerson: (nextPerson: Partial<PersonStoreState>) => void520 setPerson: (nextPerson: PersonStoreState['person']) => void521}522523type PersonStore = PersonStoreState & PersonStoreActions524525const 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}))533534export 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)537559 function handleFirstNameChange(e) {560 setPerson({ firstName: e.target.value })538 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {539 setPerson({ ...person, firstName: e.target.value })540 }541563 function handleLastNameChange(e) {564 setPerson({ lastName: e.target.value })542 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {543 setPerson({ ...person, lastName: e.target.value })544 }545567 function handleEmailChange(e) {568 setPerson({ email: e.target.value })546 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {547 setPerson({ ...person, email: e.target.value })548 }549550 return (551 <>
19 unmodified lines
modified:docs/apis/shallow.md+9 added-4 removed
10 unmodified lines
11> [!NOTE]12> Shallow lets you perform quick comparisons, but keep its limitations in mind.1314```js15shallow(a, b)15const equal = shallow(a, b)16```1718- [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)2828## Reference29## Types3030### `shallow` Signature31### Signature3233```ts34shallow<T>(a: T, b: T): boolean35```3637## Reference3839### `shallow(a, b)`4041#### Parameters4243- `a`: The first value.44- `b`: The second value.
182 unmodified lines
modified:docs/hooks/use-shallow.md+8 added-6 removed
5 unmodified lines
67`useShallow` is a React Hook that lets you optimize re-renders.89```js10useShallow(selector)10const memoizedSelector = useShallow(selector)11```1213- [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 - TBD1920## Reference20### Signature2122### `useShallow` Signature2322```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.33
231 unmodified lines
modified:docs/hooks/use-store-with-equality-fn.md+13 added-19 removed
7 unmodified lines
8`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```js12useStoreWithEqualityFn(storeApi, selectorFn, equalityFn)12const someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)13```1415- [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 - TBD2425## Reference25### Signature2627### `useStoreWithEqualityFn` Signature2827```ts30useStoreWithEqualityFn<T, U = T>(storeApi: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U28useStoreWithEqualityFn<T, U = T>(store: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U29```3031## Reference3233### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`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.
24 unmodified lines
63type PositionStore = PositionStoreState & PositionStoreActions6465const positionStore = createStore<PositionStore>()((set) => ({66 position: { x: 0, y: 0 },65 setPosition: (position) => {66 set({ position })67 },67 setPosition: (position) => set({ position }),68}))69```7071Next, we'll create a `MovingDot` component that renders a div representing the dot. This component
67 unmodified lines
139type PositionStore = PositionStoreState & PositionStoreActions140141const positionStore = createStore<PositionStore>()((set) => ({142 position: { x: 0, y: 0 },143 setPosition: (position) => {144 set({ position })145 },143 setPosition: (position) => set({ position }),144}))145146function MovingDot() {147 const position = useStoreWithEqualityFn(
291 unmodified lines
439440const 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 lines
559560const 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}566567const PositionStoreContext = createContext<ReturnType<
389 unmodified lines
modified:docs/hooks/use-store.md+14 added-18 removed
5 unmodified lines
67`useStore` is a React Hook that lets you use a vanilla store in React.89```js10useStore(storeApi, selectorFn)10const someState = useStore(store, selectorFn)11```1213- [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 - TBD2223## Reference23## Types2425### `useStore` Signature25### Signature2627```ts28useStore<StoreApi<T>, U = T>(storeApi: StoreApi<T>, selectorFn?: (state: T) => U) => UseBoundStore<StoreApi<T>>28useStore<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.
20 unmodified lines
59type PositionStore = PositionStoreState & PositionStoreActions6061const positionStore = createStore<PositionStore>()((set) => ({62 position: { x: 0, y: 0 },59 setPosition: (position) => {60 set({ position })61 },63 setPosition: (position) => set({ position }),64}))65```6667Next, we'll create a `MovingDot` component that renders a div representing the dot. This component
57 unmodified lines
125type PositionStore = PositionStoreState & PositionStoreActions126127const positionStore = createStore<PositionStore>()((set) => ({128 position: { x: 0, y: 0 },127 setPosition: (position) => {128 set({ position })129 },129 setPosition: (position) => set({ position }),130}))131132function MovingDot() {133 const position = useStore(positionStore, (state) => state.position)
275 unmodified lines
409410const 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 lines
527528const 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}534535const PositionStoreContext = createContext<ReturnType<
387 unmodified lines
added:docs/middlewares/combine.md+103 added
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/combine'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/middlewares/devtools.md+266 added
1---2title: devtools3description: How to time-travel debug your store4nav: 2055---67# devtools89`devtools` middleware lets you use [Redux DevTools Extension](https://github.com/zalmoxisus/redux-devtools-extension)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```js13const nextStateCreatorFn = devtools(stateCreatorFn, devtoolsOptions)14```1516- [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)2627## Types2829### Signature3031```ts32devtools<T>(stateCreatorFn: StateCreator<T, [], []>, devtoolsOptions?: DevtoolsOptions): StateCreator<T, [['zustand/devtools', never]], []>33```3435### Mutator3637<!-- prettier-ignore-start -->38```ts39['zustand/devtools', never]40```41<!-- prettier-ignore-end -->4243## Reference4445### `devtools(stateCreatorFn, devtoolsOptions)`4647#### Parameters4849- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.50 Usually, you will return an object with the methods you want to expose.51- **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.5960#### Returns6162`devtools` returns a state creator function.6364## Usage6566### Debugging a store6768This example shows you how you can use `Redux Devtools` to debug a store6970```ts71import { create, StateCreator } from 'zustand'7273type JungleStore = {74 bears: number75 addBear: () => void76 fishes: number77 addFish: () => void78}7980const 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```9596### Debugging a Slices pattern based store9798This example shows you how you can use `Redux Devtools` to debug a Slices pattern based store99100```ts101import { create, StateCreator } from 'zustand'102import { devtools } from 'zustand/middleware/devtools'103104type BearSlice = {105 bears: number106 addBear: () => void107}108109type FishSlice = {110 fishes: number111 addFish: () => void112}113114type JungleStore = BearSlice & FishSlice115116const 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})130131const 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})145146const useJungleStore = create<JungleStore>()(147 devtools((...args) => ({148 ...createBearSlice(...args),149 ...createFishSlice(...args),150 })),151)152```153154## Troubleshooting155156### Only one store is displayed157158By default, `Redux Devtools` only show one store at a time, so in order to see other stores you159need to use store selector and choose a different store.160161### All action names are labeled as 'anonymous'162163If an action type name is not provided, it is defaulted to "anonymous". You can customize this164default value by providing a `anonymousActionType` parameter:165166For instance the next example doesn't have action type name:167168```ts169import { create, StateCreator } from 'zustand'170import { devtools } from 'zustand/middleware/devtools'171172type BearSlice = {173 bears: number174 addBear: () => void175}176177type FishSlice = {178 fishes: number179 addFish: () => void180}181182type JungleStore = BearSlice & FishSlice183184const 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})194195const createFishSlice: StateCreator<196 JungleStore,197 [['zustand/devtools', never]],198 [],199 FishSlice200> = (set) => ({201 fishes: 0,202 addFish: () => set((state) => ({ fishes: state.fishes + 1 })),203})204205const useJungleStore = create<JungleStore>()(206 devtools((...args) => ({207 ...createBearSlice(...args),208 ...createFishSlice(...args),209 })),210)211```212213In order to fix the previous example, we need to provide an action type name as the third parameter.214Additionally, to preserve the default behavior of the replacement logic, the second parameter215should be set to `undefined`.216217Here's the fixed previous example218219```ts220import { create, StateCreator } from 'zustand'221222type BearSlice = {223 bears: number224 addBear: () => void225}226227type FishSlice = {228 fishes: number229 addFish: () => void230}231232type JungleStore = BearSlice & FishSlice233234const 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})244245const 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})255256const useJungleStore = create<JungleStore>()(257 devtools((...args) => ({258 ...createBearSlice(...args),259 ...createFishSlice(...args),260 })),261)262```263264> [!IMPORTANT]265> Do not set the second parameter to `true` or `false` unless you want to override the default266> replacement logic
added:docs/middlewares/immer.md+232 added
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```js12const nextStateCreatorFn = immer(stateCreatorFn)13```1415- [Types](#types)16 - [Signature](#signature)17 - [Mutator](#mutator)18- [Reference](#reference)19- [Usage](#usage)20- [Troubleshooting](#troubleshooting)2122## Types2324### Signature2526```ts27immer<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/immer', never]], []>28```2930### Mutator3132<!-- prettier-ignore-start -->33```ts34['zustand/immer', never]35```36<!-- prettier-ignore-end -->3738## Reference3940### `immer(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`immer` returns a state creator function.5051## Usage5253### Updating state without boilerplate code5455In the next example, we're going to update the `person` object. Since it's a nested object, we need56to create a copy of the entire object before making the update.5758```ts59import { createStore } from 'zustand/vanilla'6061type PersonStoreState = {62 person: { firstName: string; lastName: string; email: string }63}6465type PersonStoreActions = {66 setPerson: (67 nextPerson: (68 person: PersonStoreState['person'],69 ) => PersonStoreState['person'] | PersonStoreState['person'],70 ) => void71}7273type PersonStore = PersonStoreState & PersonStoreActions7475const 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}))8990const $firstNameInput = document.getElementById(91 'first-name',92) as HTMLInputElement93const $lastNameInput = document.getElementById('last-name') as HTMLInputElement94const $emailInput = document.getElementById('email') as HTMLInputElement95const $result = document.getElementById('result') as HTMLDivElement9697function handleFirstNameChange(event: Event) {98 personStore.getState().setPerson((person) => ({99 ...person,100 firstName: (event.target as any).value,101 }))102}103104function handleLastNameChange(event: Event) {105 personStore.getState().setPerson((person) => ({106 ...person,107 lastName: (event.target as any).value,108 }))109}110111function handleEmailChange(event: Event) {112 personStore.getState().setPerson((person) => ({113 ...person,114 email: (event.target as any).value,115 }))116}117118$firstNameInput.addEventListener('input', handleFirstNameChange)119$lastNameInput.addEventListener('input', handleLastNameChange)120$emailInput.addEventListener('input', handleEmailChange)121122const render: Parameters<typeof personStore.subscribe>[0] = (state) => {123 $firstNameInput.value = state.person.firstName124 $lastNameInput.value = state.person.lastName125 $emailInput.value = state.person.email126127 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`128}129130render(personStore.getInitialState(), personStore.getInitialState())131132personStore.subscribe(render)133```134135Here's the `html` code136137```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```152153To avoid manually copying the entire object before making updates, we'll use the `immer`154middleware.155156```ts157import { createStore } from 'zustand/vanilla'158import { immer } from 'zustand/middleware/immer'159160type PersonStoreState = {161 person: { firstName: string; lastName: string; email: string }162}163164type PersonStoreActions = {165 setPerson: (166 nextPerson: (167 person: PersonStoreState['person'],168 ) => PersonStoreState['person'] | PersonStoreState['person'],169 ) => void170}171172type PersonStore = PersonStoreState & PersonStoreActions173174const 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)187188const $firstNameInput = document.getElementById(189 'first-name',190) as HTMLInputElement191const $lastNameInput = document.getElementById('last-name') as HTMLInputElement192const $emailInput = document.getElementById('email') as HTMLInputElement193const $result = document.getElementById('result') as HTMLDivElement194195function handleFirstNameChange(event: Event) {196 personStore.getState().setPerson((person) => {197 person.firstName = (event.target as any).value198 })199}200201function handleLastNameChange(event: Event) {202 personStore.getState().setPerson((person) => {203 person.lastName = (event.target as any).value204 })205}206207function handleEmailChange(event: Event) {208 personStore.getState().setPerson((person) => {209 person.email = (event.target as any).value210 })211}212213$firstNameInput.addEventListener('input', handleFirstNameChange)214$lastNameInput.addEventListener('input', handleLastNameChange)215$emailInput.addEventListener('input', handleEmailChange)216217const render: Parameters<typeof personStore.subscribe>[0] = (state) => {218 $firstNameInput.value = state.person.firstName219 $lastNameInput.value = state.person.lastName220 $emailInput.value = state.person.email221222 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`223}224225render(personStore.getInitialState(), personStore.getInitialState())226227personStore.subscribe(render)228```229230## Troubleshooting231232TBD
added:docs/middlewares/persist.md+988 added
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
added:docs/middlewares/redux.md+170 added
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/redux'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 & PersonStoreActions7475const 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}9495const personStoreInitialState: PersonStoreState = {96 firstName: 'Barbara',97 lastName: 'Hepworth',98 email: 'bhepworth@sculpture.com',99}100101const personStore = createStore<PersonStore>()(102 redux(personStoreReducer, personStoreInitialState),103)104105const $firstNameInput = document.getElementById(106 'first-name',107) as HTMLInputElement108const $lastNameInput = document.getElementById('last-name') as HTMLInputElement109const $emailInput = document.getElementById('email') as HTMLInputElement110const $result = document.getElementById('result') as HTMLDivElement111112function handleFirstNameChange(event: Event) {113 personStore.dispatch({114 type: 'person/setFirstName',115 firstName: (event.target as any).value,116 })117}118119function handleLastNameChange(event: Event) {120 personStore.dispatch({121 type: 'person/setLastName',122 lastName: (event.target as any).value,123 })124}125126function handleEmailChange(event: Event) {127 personStore.dispatch({128 type: 'person/setEmail',129 email: (event.target as any).value,130 })131}132133$firstNameInput.addEventListener('input', handleFirstNameChange)134$lastNameInput.addEventListener('input', handleLastNameChange)135$emailInput.addEventListener('input', handleEmailChange)136137const render: Parameters<typeof personStore.subscribe>[0] = (person) => {138 $firstNameInput.value = person.firstName139 $lastNameInput.value = person.lastName140 $emailInput.value = person.email141142 $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`143}144145render(personStore.getInitialState(), personStore.getInitialState())146147personStore.subscribe(render)148```149150Here's the `html` code151152```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```167168## Troubleshooting169170TBD
added:docs/middlewares/subscribe-with-selector.md+121 added
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/subscribeWithSelector'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