Revamping docs - file restructuring (#3392)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: file restructuring * feat: update docs gh workflow * feat: update docs order * feat: update docs * feat: clean up * feat: fix linting * feat: moving config files to rspress theme config
authored by Danilo Britto · committed by GitHub · parent 9c6dff7 · Browse files · 87 files·+13307 added−13219 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
87 files+13307 added−13219 removed
- other:+13307 added−13219 removed
Provenance
- Commit
8eae4e9- Tree
abb67f7- Author
Danilo Britto <dbritto.dev@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
9c6dff7
87 files changed+13307 added−13219 removed
modified:.github/workflows/docs.yml+3 added-3 removed
14 unmodified lines151617181920211920212223242515 unmodified lines14 unmodified lines uses: pmndrs/docs/.github/workflows/build.yml@v2 # v2.20.4 with: mdx: 'docs' libname: 'Zustand' home_redirect: '/getting-started/introduction' icon: '/favicon.ico' logo: '/bear.jpg' home_redirect: '/learn/getting-started/introduction' icon: '/public/favicon.ico' logo: '/public/bear.jpg' github: 'https://github.com/pmndrs/zustand'
deploy: needs: build15 unmodified linesdeleted:docs/apis/create-store.md-517 removed
1----2-title: createStore3-description: How to create vanilla stores4-nav: 245----6-7-`createStore` lets you create a vanilla store that exposes API utilities.8-9-```js10-const someStore = createStore(stateCreatorFn)11-```12-13-- [Types](#types)14- - [Signature](#signature)15-- [Reference](#reference)16-- [Usage](#usage)17- - [Updating state based on previous state](#updating-state-based-on-previous-state)18- - [Updating Primitives in State](#updating-primitives-in-state)19- - [Updating Objects in State](#updating-objects-in-state)20- - [Updating Arrays in State](#updating-arrays-in-state)21- - [Subscribing to state updates](#subscribing-to-state-updates)22-- [Troubleshooting](#troubleshooting)23- - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)24-25-## Types26-27-### Signature28-29-```ts30-createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>31-```32-33-## Reference34-35-### `createStore(stateCreatorFn)`36-37-#### Parameters38-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-44-`createStore` returns a vanilla store that exposes API utilities, `setState`, `getState`,45-`getInitialState` and `subscribe`.46-47-## Usage48-49-### Updating state based on previous state50-51-This example shows how you can support **updater functions** within **actions**.52-53-```tsx54-import { createStore } from 'zustand/vanilla'55-56-type AgeStoreState = { age: number }57-58-type AgeStoreActions = {59- setAge: (60- nextAge:61- | AgeStoreState['age']62- | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),63- ) => void64-}65-66-type AgeStore = AgeStoreState & AgeStoreActions67-68-const ageStore = createStore<AgeStore>()((set) => ({69- age: 42,70- setAge: (nextAge) =>71- set((state) => ({72- age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,73- })),74-}))75-76-function increment() {77- ageStore.getState().setAge((currentAge) => currentAge + 1)78-}79-80-const $yourAgeHeading = document.getElementById(81- 'your-age',82-) as HTMLHeadingElement83-const $incrementBy3Button = document.getElementById(84- 'increment-by-3',85-) as HTMLButtonElement86-const $incrementBy1Button = document.getElementById(87- 'increment-by-1',88-) as HTMLButtonElement89-90-$incrementBy3Button.addEventListener('click', () => {91- increment()92- increment()93- increment()94-})95-96-$incrementBy1Button.addEventListener('click', () => {97- increment()98-})99-100-const render: Parameters<typeof ageStore.subscribe>[0] = (state) => {101- $yourAgeHeading.innerHTML = `Your age: ${state.age}`102-}103-104-render(ageStore.getInitialState(), ageStore.getInitialState())105-106-ageStore.subscribe(render)107-```108-109-Here's the `html` code110-111-```html112-<h1 id="your-age"></h1>113-<button id="increment-by-3" type="button">+3</button>114-<button id="increment-by-1" type="button">+1</button>115-```116-117-### Updating Primitives in State118-119-State can hold any kind of JavaScript value. When you want to update built-in primitive values like120-numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied121-correctly, and avoid unexpected behaviors.122-123-> [!NOTE]124-> By default, `set` function performs a shallow merge. If you need to completely replace125-> the state with a new one, use the `replace` parameter set to `true`126-127-```ts128-import { createStore } from 'zustand/vanilla'129-130-type XStore = number131-132-const xStore = createStore<XStore>()(() => 0)133-134-const $dotContainer = document.getElementById('dot-container') as HTMLDivElement135-const $dot = document.getElementById('dot') as HTMLDivElement136-137-$dotContainer.addEventListener('pointermove', (event) => {138- xStore.setState(event.clientX, true)139-})140-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-147-xStore.subscribe(render)148-```149-150-Here's the `html` code151-152-```html153-<div154- id="dot-container"155- style="position: relative; width: 100vw; height: 100vh;"156->157- <div158- id="dot"159- style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"160- ></div>161-</div>162-```163-164-### Updating Objects in State165-166-Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store167-them in state. Instead, when you want to update an object, you need to create a new one (or make a168-copy of an existing one), and then set the state to use the new object.169-170-By default, `set` function performs a shallow merge. For most updates where you only need to modify171-specific properties, the default shallow merge is preferred as it's more efficient. To completely172-replace the state with a new one, use the `replace` parameter set to `true` with caution, as it173-discards any existing nested data within the state.174-175-```ts176-import { createStore } from 'zustand/vanilla'177-178-type PositionStoreState = { position: { x: number; y: number } }179-180-type PositionStoreActions = {181- setPosition: (nextPosition: PositionStoreState['position']) => void182-}183-184-type PositionStore = PositionStoreState & PositionStoreActions185-186-const positionStore = createStore<PositionStore>()((set) => ({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 HTMLDivElement193-194-$dotContainer.addEventListener('pointermove', (event) => {195- positionStore.getState().setPosition({196- x: event.clientX,197- y: event.clientY,198- })199-})200-201-const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {202- $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`203-}204-205-render(positionStore.getInitialState(), positionStore.getInitialState())206-207-positionStore.subscribe(render)208-```209-210-Here's the `html` code211-212-```html213-<div214- id="dot-container"215- style="position: relative; width: 100vw; height: 100vh;"216->217- <div218- id="dot"219- style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"220- ></div>221-</div>222-```223-224-### Updating Arrays in State225-226-Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in227-state. Just like with objects, when you want to update an array stored in state, you need to create228-a new one (or make a copy of an existing one), and then set state to use the new array.229-230-By default, `set` function performs a shallow merge. To update array values we should assign new231-values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely232-replace the state with a new one, use the `replace` parameter set to `true`.233-234-> [!IMPORTANT]235-> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,236-> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid237-> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,238-> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.239-240-```ts241-import { createStore } from 'zustand/vanilla'242-243-type PositionStore = [number, number]244-245-const positionStore = createStore<PositionStore>()(() => [0, 0])246-247-const $dotContainer = document.getElementById('dot-container') as HTMLDivElement248-const $dot = document.getElementById('dot') as HTMLDivElement249-250-$dotContainer.addEventListener('pointermove', (event) => {251- positionStore.setState([event.clientX, event.clientY], true)252-})253-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-260-positionStore.subscribe(render)261-```262-263-Here's the `html` code264-265-```html266-<div267- id="dot-container"268- style="position: relative; width: 100vw; height: 100vh;"269->270- <div271- id="dot"272- style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"273- ></div>274-</div>275-```276-277-### Subscribing to state updates278-279-By subscribing to state updates, you register a callback that fires whenever the store's state280-updates. We can use `subscribe` for external state management.281-282-```ts283-import { createStore } from 'zustand/vanilla'284-285-type PositionStoreState = { position: { x: number; y: number } }286-287-type PositionStoreActions = {288- setPosition: (nextPosition: PositionStoreState['position']) => void289-}290-291-type PositionStore = PositionStoreState & PositionStoreActions292-293-const positionStore = createStore<PositionStore>()((set) => ({294- position: { x: 0, y: 0 },295- setPosition: (position) => set({ position }),296-}))297-298-const $dot = document.getElementById('dot') as HTMLDivElement299-300-$dot.addEventListener('mouseenter', (event) => {301- const parent = event.currentTarget.parentElement302- const parentWidth = parent.clientWidth303- const parentHeight = parent.clientHeight304-305- positionStore.getState().setPosition({306- x: Math.ceil(Math.random() * parentWidth),307- y: Math.ceil(Math.random() * parentHeight),308- })309-})310-311-const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {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) => {320- console.log('new position', { position: state.position })321-}322-323-positionStore.subscribe(logger)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-## Troubleshooting341-342-### I’ve updated the state, but the screen doesn’t update343-344-In the previous example, the `position` object is always created fresh from the current cursor345-position. But often, you will want to include existing data as a part of the new object you’re346-creating. For example, you may want to update only one field in a form, but keep the previous347-values for all other fields.348-349-These input fields don’t work because the `oninput` handlers mutate the state:350-351-```ts352-import { createStore } from 'zustand/vanilla'353-354-type PersonStoreState = {355- person: { firstName: string; lastName: string; email: string }356-}357-358-type PersonStoreActions = {359- setPerson: (nextPerson: PersonStoreState['person']) => void360-}361-362-type PersonStore = PersonStoreState & PersonStoreActions363-364-const personStore = createStore<PersonStore>()((set) => ({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',375-) as HTMLInputElement376-const $lastNameInput = document.getElementById('last-name') as HTMLInputElement377-const $emailInput = document.getElementById('email') as HTMLInputElement378-const $result = document.getElementById('result') as HTMLDivElement379-380-function handleFirstNameChange(event: Event) {381- personStore.getState().person.firstName = (event.target as any).value382-}383-384-function handleLastNameChange(event: Event) {385- personStore.getState().person.lastName = (event.target as any).value386-}387-388-function handleEmailChange(event: Event) {389- 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) => {397- $firstNameInput.value = state.person.firstName398- $lastNameInput.value = state.person.lastName399- $emailInput.value = state.person.email400-401- $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`402-}403-404-render(personStore.getInitialState(), personStore.getInitialState())405-406-personStore.subscribe(render)407-```408-409-Here's the `html` code410-411-```html412-<label style="display: block">413- First name:414- <input id="first-name" />415-</label>416-<label style="display: block">417- Last name:418- <input id="last-name" />419-</label>420-<label style="display: block">421- Email:422- <input id="email" />423-</label>424-<p id="result"></p>425-```426-427-For example, this line mutates the state from a past render:428-429-```ts430-personStore.getState().firstName = (e.target as any).value431-```432-433-The reliable way to get the behavior you’re looking for is to create a new object and pass it to434-`setPerson`. But here you want to also copy the existing data into it because only one of the435-fields has changed:436-437-```ts438-personStore.getState().setPerson({439- firstName: e.target.value, // New first name from the input440-})441-```442-443-> [!NOTE]444-> We don’t need to copy every property separately due to `set` function performing shallow merge by445-> default.446-447-Now the form works!448-449-Notice how you didn’t declare a separate state variable for each input field. For large forms,450-keeping all data grouped in an object is very convenient—as long as you update it correctly!451-452-```ts {32-34,38-40,44-46}453-import { createStore } from 'zustand/vanilla'454-455-type PersonStoreState = {456- person: { firstName: string; lastName: string; email: string }457-}458-459-type PersonStoreActions = {460- setPerson: (nextPerson: PersonStoreState['person']) => void461-}462-463-type PersonStore = PersonStoreState & PersonStoreActions464-465-const personStore = createStore<PersonStore>()((set) => ({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',476-) as HTMLInputElement477-const $lastNameInput = document.getElementById('last-name') as HTMLInputElement478-const $emailInput = document.getElementById('email') as HTMLInputElement479-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-502-$firstNameInput.addEventListener('input', handleFirstNameChange)503-$lastNameInput.addEventListener('input', handleLastNameChange)504-$emailInput.addEventListener('input', handleEmailChange)505-506-const render: Parameters<typeof personStore.subscribe>[0] = (state) => {507- $firstNameInput.value = state.person.firstName508- $lastNameInput.value = state.person.lastName509- $emailInput.value = state.person.email510-511- $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`512-}513-514-render(personStore.getInitialState(), personStore.getInitialState())515-516-personStore.subscribe(render)517-```deleted:docs/apis/create-with-equality-fn.md-606 removed
1----2-title: createWithEqualityFn ⚛️3-description: How to create efficient stores4-nav: 255----6-7-`createWithEqualityFn` lets you create a React Hook with API utilities attached, just like `create`.8-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-> [!IMPORTANT]12-> In order to use `createWithEqualityFn` from `zustand/traditional` you need to install13-> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.14-15-```js16-const useSomeStore = createWithEqualityFn(stateCreatorFn, equalityFn)17-```18-19-- [Types](#types)20- - [Signature](#createwithequalityfn-signature)21-- [Reference](#reference)22-- [Usage](#usage)23- - [Updating state based on previous state](#updating-state-based-on-previous-state)24- - [Updating Primitives in State](#updating-primitives-in-state)25- - [Updating Objects in State](#updating-objects-in-state)26- - [Updating Arrays in State](#updating-arrays-in-state)27- - [Updating state with no store actions](#updating-state-with-no-store-actions)28- - [Subscribing to state updates](#subscribing-to-state-updates)29-- [Troubleshooting](#troubleshooting)30- - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)31-32-## Types33-34-### Signature35-36-```ts37-createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, equalityFn?: (a: T, b: T) => boolean): UseBoundStore<StoreApi<T>>38-```39-40-## Reference41-42-### `createWithEqualityFn(stateCreatorFn)`43-44-#### Parameters45-46-- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.47- Usually, you will return an object with the methods you want to expose.48-- **optional** `equalityFn`: Defaults to `Object.is`. A function that lets you skip re-renders.49-50-#### Returns51-52-`createWithEqualityFn` returns a React Hook with API utilities attached, just like `create`. It53-lets you return data that is based on current state, using a selector function, and lets you skip54-re-renders using an equality function. It should take a selector function, and an equality function55-as arguments.56-57-## Usage58-59-### Updating state based on previous state60-61-To update a state based on previous state we should use **updater functions**. Read more62-about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).63-64-This example shows how you can support **updater functions** within **actions**.65-66-```tsx67-import { createWithEqualityFn } from 'zustand/traditional'68-import { shallow } from 'zustand/vanilla/shallow'69-70-type AgeStoreState = { age: number }71-72-type AgeStoreActions = {73- setAge: (74- nextAge:75- | AgeStoreState['age']76- | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),77- ) => void78-}79-80-type AgeStore = AgeStoreState & AgeStoreActions81-82-const useAgeStore = createWithEqualityFn<AgeStore>()(83- (set) => ({84- age: 42,85- setAge: (nextAge) =>86- set((state) => ({87- age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,88- })),89- }),90- shallow,91-)92-93-export default function App() {94- const age = useAgeStore((state) => state.age)95- const setAge = useAgeStore((state) => state.setAge)96-97- function increment() {98- setAge((currentAge) => currentAge + 1)99- }100-101- return (102- <>103- <h1>Your age: {age}</h1>104- <button105- type="button"106- onClick={() => {107- increment()108- increment()109- increment()110- }}111- >112- +3113- </button>114- <button115- type="button"116- onClick={() => {117- increment()118- }}119- >120- +1121- </button>122- </>123- )124-}125-```126-127-### Updating Primitives in State128-129-State can hold any kind of JavaScript value. When you want to update built-in primitive values like130-numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied131-correctly, and avoid unexpected behaviors.132-133-> [!NOTE]134-> By default, `set` function performs a shallow merge. If you need to completely replace135-> the state with a new one, use the `replace` parameter set to `true`136-137-```tsx138-import { createWithEqualityFn } from 'zustand/traditional'139-import { shallow } from 'zustand/vanilla/shallow'140-141-type XStore = number142-143-const useXStore = createWithEqualityFn<XStore>()(() => 0, shallow)144-145-export default function MovingDot() {146- const x = useXStore()147- const setX = (nextX: number) => {148- useXStore.setState(nextX, true)149- }150- const position = { y: 0, x }151-152- return (153- <div154- onPointerMove={(e) => {155- setX(e.clientX)156- }}157- style={{158- position: 'relative',159- width: '100vw',160- height: '100vh',161- }}162- >163- <div164- style={{165- position: 'absolute',166- backgroundColor: 'red',167- borderRadius: '50%',168- transform: `translate(${position.x}px, ${position.y}px)`,169- left: -10,170- top: -10,171- width: 20,172- height: 20,173- }}174- />175- </div>176- )177-}178-```179-180-### Updating Objects in State181-182-Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store183-them in state. Instead, when you want to update an object, you need to create a new one (or make a184-copy of an existing one), and then set the state to use the new object.185-186-By default, `set` function performs a shallow merge. For most updates where you only need to modify187-specific properties, the default shallow merge is preferred as it's more efficient. To completely188-replace the state with a new one, use the `replace` parameter set to `true` with caution, as it189-discards any existing nested data within the state.190-191-```tsx192-import { createWithEqualityFn } from 'zustand/traditional'193-import { shallow } from 'zustand/vanilla/shallow'194-195-type PositionStoreState = { position: { x: number; y: number } }196-197-type PositionStoreActions = {198- setPosition: (nextPosition: PositionStoreState['position']) => void199-}200-201-type PositionStore = PositionStoreState & PositionStoreActions202-203-const usePositionStore = createWithEqualityFn<PositionStore>()(204- (set) => ({205- position: { x: 0, y: 0 },206- setPosition: (position) => set({ position }),207- }),208- shallow,209-)210-211-export default function MovingDot() {212- const position = usePositionStore((state) => state.position)213- const setPosition = usePositionStore((state) => state.setPosition)214-215- return (216- <div217- onPointerMove={(e) => {218- setPosition({219- x: e.clientX,220- y: e.clientY,221- })222- }}223- style={{224- position: 'relative',225- width: '100vw',226- height: '100vh',227- }}228- >229- <div230- style={{231- position: 'absolute',232- backgroundColor: 'red',233- borderRadius: '50%',234- transform: `translate(${position.x}px, ${position.y}px)`,235- left: -10,236- top: -10,237- width: 20,238- height: 20,239- }}240- />241- </div>242- )243-}244-```245-246-### Updating Arrays in State247-248-Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in249-state. Just like with objects, when you want to update an array stored in state, you need to create250-a new one (or make a copy of an existing one), and then set state to use the new array.251-252-By default, `set` function performs a shallow merge. To update array values we should assign new253-values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely254-replace the state with a new one, use the `replace` parameter set to `true`.255-256-> [!IMPORTANT]257-> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,258-> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid259-> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,260-> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.261-262-```tsx263-import { createWithEqualityFn } from 'zustand/traditional'264-import { shallow } from 'zustand/vanilla/shallow'265-266-type PositionStore = [number, number]267-268-const usePositionStore = createWithEqualityFn<PositionStore>()(269- () => [0, 0],270- shallow,271-)272-273-export default function MovingDot() {274- const [x, y] = usePositionStore()275- const position = { x, y }276- const setPosition: typeof usePositionStore.setState = (nextPosition) => {277- usePositionStore.setState(nextPosition, true)278- }279-280- return (281- <div282- onPointerMove={(e) => {283- setPosition([e.clientX, e.clientY])284- }}285- style={{286- position: 'relative',287- width: '100vw',288- height: '100vh',289- }}290- >291- <div292- style={{293- position: 'absolute',294- backgroundColor: 'red',295- borderRadius: '50%',296- transform: `translate(${position.x}px, ${position.y}px)`,297- left: -10,298- top: -10,299- width: 20,300- height: 20,301- }}302- />303- </div>304- )305-}306-```307-308-### Updating state with no store actions309-310-Defining actions at module level, external to the store have a few advantages like: it doesn't311-require a hook to call an action, and it facilitates code splitting.312-313-> [!NOTE]314-> The recommended way is to colocate actions and states within the store (let your actions be315-> located together with your state).316-317-```tsx318-import { createWithEqualityFn } from 'zustand/traditional'319-import { shallow } from 'zustand/vanilla/shallow'320-321-const usePositionStore = createWithEqualityFn<{322- x: number323- y: number324-}>()(() => ({ x: 0, y: 0 }), shallow)325-326-const setPosition: typeof usePositionStore.setState = (nextPosition) => {327- usePositionStore.setState(nextPosition)328-}329-330-export default function MovingDot() {331- const position = usePositionStore()332-333- return (334- <div335- style={{336- position: 'relative',337- width: '100vw',338- height: '100vh',339- }}340- >341- <div342- style={{343- position: 'absolute',344- backgroundColor: 'red',345- borderRadius: '50%',346- transform: `translate(${position.x}px, ${position.y}px)`,347- left: -10,348- top: -10,349- width: 20,350- height: 20,351- }}352- onMouseEnter={(event) => {353- const parent = event.currentTarget.parentElement354- const parentWidth = parent.clientWidth355- const parentHeight = parent.clientHeight356-357- setPosition({358- x: Math.ceil(Math.random() * parentWidth),359- y: Math.ceil(Math.random() * parentHeight),360- })361- }}362- />363- </div>364- )365-}366-```367-368-### Subscribing to state updates369-370-By subscribing to state updates, you register a callback that fires whenever the store's state371-updates. We can use `subscribe` for external state management.372-373-```tsx374-import { useEffect } from 'react'375-import { createWithEqualityFn } from 'zustand/traditional'376-import { shallow } from 'zustand/vanilla/shallow'377-378-type PositionStoreState = { position: { x: number; y: number } }379-380-type PositionStoreActions = {381- setPosition: (nextPosition: PositionStoreState['position']) => void382-}383-384-type PositionStore = PositionStoreState & PositionStoreActions385-386-const usePositionStore = createWithEqualityFn<PositionStore>()(387- (set) => ({388- position: { x: 0, y: 0 },389- setPosition: (nextPosition) => set({ position: nextPosition }),390- }),391- shallow,392-)393-394-export default function MovingDot() {395- const position = usePositionStore((state) => state.position)396- const setPosition = usePositionStore((state) => state.setPosition)397-398- useEffect(() => {399- const unsubscribePositionStore = usePositionStore.subscribe(400- ({ position }) => {401- console.log('new position', { position })402- },403- )404-405- return () => {406- unsubscribePositionStore()407- }408- }, [])409-410- return (411- <div412- style={{413- position: 'relative',414- width: '100vw',415- height: '100vh',416- }}417- >418- <div419- style={{420- position: 'absolute',421- backgroundColor: 'red',422- borderRadius: '50%',423- transform: `translate(${position.x}px, ${position.y}px)`,424- left: -10,425- top: -10,426- width: 20,427- height: 20,428- }}429- onMouseEnter={(event) => {430- const parent = event.currentTarget.parentElement431- const parentWidth = parent.clientWidth432- const parentHeight = parent.clientHeight433-434- setPosition({435- x: Math.ceil(Math.random() * parentWidth),436- y: Math.ceil(Math.random() * parentHeight),437- })438- }}439- />440- </div>441- )442-}443-```444-445-## Troubleshooting446-447-### I’ve updated the state, but the screen doesn’t update448-449-In the previous example, the `position` object is always created fresh from the current cursor450-position. But often, you will want to include existing data as a part of the new object you’re451-creating. For example, you may want to update only one field in a form, but keep the previous452-values for all other fields.453-454-These input fields don’t work because the `onChange` handlers mutate the state:455-456-```tsx457-import { createWithEqualityFn } from 'zustand/traditional'458-import { shallow } from 'zustand/vanilla/shallow'459-460-type PersonStoreState = {461- person: { firstName: string; lastName: string; email: string }462-}463-464-type PersonStoreActions = {465- setPerson: (nextPerson: PersonStoreState['person']) => void466-}467-468-type PersonStore = PersonStoreState & PersonStoreActions469-470-const usePersonStore = createWithEqualityFn<PersonStore>()(471- (set) => ({472- person: {473- firstName: 'Barbara',474- lastName: 'Hepworth',475- email: 'bhepworth@sculpture.com',476- },477- setPerson: (person) => set({ person }),478- }),479- shallow,480-)481-482-export default function Form() {483- const person = usePersonStore((state) => state.person)484- const setPerson = usePersonStore((state) => state.setPerson)485-486- function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {487- person.firstName = e.target.value488- }489-490- function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {491- person.lastName = e.target.value492- }493-494- function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {495- person.email = e.target.value496- }497-498- return (499- <>500- <label style={{ display: 'block' }}>501- First name:502- <input value={person.firstName} onChange={handleFirstNameChange} />503- </label>504- <label style={{ display: 'block' }}>505- Last name:506- <input value={person.lastName} onChange={handleLastNameChange} />507- </label>508- <label style={{ display: 'block' }}>509- Email:510- <input value={person.email} onChange={handleEmailChange} />511- </label>512- <p>513- {person.firstName} {person.lastName} ({person.email})514- </p>515- </>516- )517-}518-```519-520-For example, this line mutates the state from a past render:521-522-```tsx523-person.firstName = e.target.value524-```525-526-The reliable way to get the behavior you’re looking for is to create a new object and pass it to527-`setPerson`. But here you want to also copy the existing data into it because only one of the528-fields has changed:529-530-```ts531-setPerson({ ...person, firstName: e.target.value }) // New first name from the input532-```533-534-> [!NOTE]535-> We don’t need to copy every property separately due to `set` function performing shallow merge by536-> default.537-538-Now the form works!539-540-Notice how you didn’t declare a separate state variable for each input field. For large forms,541-keeping all data grouped in an object is very convenient—as long as you update it correctly!542-543-```tsx {32,36,40}544-import { type ChangeEvent } from 'react'545-import { createWithEqualityFn } from 'zustand/traditional'546-import { shallow } from 'zustand/vanilla/shallow'547-548-type PersonStoreState = {549- person: { firstName: string; lastName: string; email: string }550-}551-552-type PersonStoreActions = {553- setPerson: (nextPerson: PersonStoreState['person']) => void554-}555-556-type PersonStore = PersonStoreState & PersonStoreActions557-558-const usePersonStore = createWithEqualityFn<PersonStore>()(559- (set) => ({560- person: {561- firstName: 'Barbara',562- lastName: 'Hepworth',563- email: 'bhepworth@sculpture.com',564- },565- setPerson: (nextPerson) => set({ person: nextPerson }),566- }),567- shallow,568-)569-570-export default function Form() {571- const person = usePersonStore((state) => state.person)572- const setPerson = usePersonStore((state) => state.setPerson)573-574- function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {575- setPerson({ ...person, firstName: e.target.value })576- }577-578- function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {579- setPerson({ ...person, lastName: e.target.value })580- }581-582- function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {583- setPerson({ ...person, email: e.target.value })584- }585-586- return (587- <>588- <label style={{ display: 'block' }}>589- First name:590- <input value={person.firstName} onChange={handleFirstNameChange} />591- </label>592- <label style={{ display: 'block' }}>593- Last name:594- <input value={person.lastName} onChange={handleLastNameChange} />595- </label>596- <label style={{ display: 'block' }}>597- Email:598- <input value={person.email} onChange={handleEmailChange} />599- </label>600- <p>601- {person.firstName} {person.lastName} ({person.email})602- </p>603- </>604- )605-}606-```deleted:docs/apis/create.md-570 removed
1----2-title: create ⚛️3-description: How to create stores4-nav: 265----6-7-`create` lets you create a React Hook with API utilities attached.8-9-```js10-const useSomeStore = create(stateCreatorFn)11-```12-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)20- - [Updating Arrays in State](#updating-arrays-in-state)21- - [Updating state with no store actions](#updating-state-with-no-store-actions)22- - [Subscribing to state updates](#subscribing-to-state-updates)23-- [Troubleshooting](#troubleshooting)24- - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)25-26-## Types27-28-### Signature29-30-```ts31-create<T>()(stateCreatorFn: StateCreator<T, [], []>): UseBoundStore<StoreApi<T>>32-```33-34-## Reference35-36-### `create(stateCreatorFn)`37-38-#### Parameters39-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-45-`create` returns a React Hook with API utilities, `setState`, `getState`, `getInitialState` and46-`subscribe`, attached. It lets you return data that is based on current state, using a selector47-function. It should take a selector function as its only argument.48-49-## Usage50-51-### Updating state based on previous state52-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-56-This example shows how you can support **updater functions** within **actions**.57-58-```tsx59-import { create } from 'zustand'60-61-type AgeStoreState = { age: number }62-63-type AgeStoreActions = {64- setAge: (65- nextAge:66- | AgeStoreState['age']67- | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),68- ) => void69-}70-71-type AgeStore = AgeStoreState & AgeStoreActions72-73-const useAgeStore = create<AgeStore>()((set) => ({74- age: 42,75- setAge: (nextAge) => {76- set((state) => ({77- age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,78- }))79- },80-}))81-82-export default function App() {83- const age = useAgeStore((state) => state.age)84- const setAge = useAgeStore((state) => state.setAge)85-86- function increment() {87- setAge((currentAge) => currentAge + 1)88- }89-90- return (91- <>92- <h1>Your age: {age}</h1>93- <button94- onClick={() => {95- increment()96- increment()97- increment()98- }}99- >100- +3101- </button>102- <button103- onClick={() => {104- increment()105- }}106- >107- +1108- </button>109- </>110- )111-}112-```113-114-### Updating Primitives in State115-116-State can hold any kind of JavaScript value. When you want to update built-in primitive values like117-numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied118-correctly, and avoid unexpected behaviors.119-120-> [!NOTE]121-> By default, `set` function performs a shallow merge. If you need to completely replace the state122-> with a new one, use the `replace` parameter set to `true`123-124-```tsx125-import { create } from 'zustand'126-127-type XStore = number128-129-const useXStore = create<XStore>()(() => 0)130-131-export default function MovingDot() {132- const x = useXStore()133- const setX = (nextX: number) => {134- useXStore.setState(nextX, true)135- }136- const position = { y: 0, x }137-138- return (139- <div140- onPointerMove={(e) => {141- setX(e.clientX)142- }}143- style={{144- position: 'relative',145- width: '100vw',146- height: '100vh',147- }}148- >149- <div150- style={{151- position: 'absolute',152- backgroundColor: 'red',153- borderRadius: '50%',154- transform: `translate(${position.x}px, ${position.y}px)`,155- left: -10,156- top: -10,157- width: 20,158- height: 20,159- }}160- />161- </div>162- )163-}164-```165-166-### Updating Objects in State167-168-Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store169-them in state. Instead, when you want to update an object, you need to create a new one (or make a170-copy of an existing one), and then set the state to use the new object.171-172-By default, `set` function performs a shallow merge. For most updates where you only need to modify173-specific properties, the default shallow merge is preferred as it's more efficient. To completely174-replace the state with a new one, use the `replace` parameter set to `true` with caution, as it175-discards any existing nested data within the state.176-177-```tsx178-import { create } from 'zustand'179-180-type PositionStoreState = { position: { x: number; y: number } }181-182-type PositionStoreActions = {183- setPosition: (nextPosition: PositionStoreState['position']) => void184-}185-186-type PositionStore = PositionStoreState & PositionStoreActions187-188-const usePositionStore = create<PositionStore>()((set) => ({189- position: { x: 0, y: 0 },190- setPosition: (nextPosition) => set({ position: nextPosition }),191-}))192-193-export default function MovingDot() {194- const position = usePositionStore((state) => state.position)195- const setPosition = usePositionStore((state) => state.setPosition)196-197- return (198- <div199- onPointerMove={(e) => {200- setPosition({201- x: e.clientX,202- y: e.clientY,203- })204- }}205- style={{206- position: 'relative',207- width: '100vw',208- height: '100vh',209- }}210- >211- <div212- style={{213- position: 'absolute',214- backgroundColor: 'red',215- borderRadius: '50%',216- transform: `translate(${position.x}px, ${position.y}px)`,217- left: -10,218- top: -10,219- width: 20,220- height: 20,221- }}222- />223- </div>224- )225-}226-```227-228-### Updating Arrays in State229-230-Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in231-state. Just like with objects, when you want to update an array stored in state, you need to create232-a new one (or make a copy of an existing one), and then set state to use the new array.233-234-By default, `set` function performs a shallow merge. To update array values we should assign new235-values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely236-replace the state with a new one, use the `replace` parameter set to `true`.237-238-> [!IMPORTANT]239-> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,240-> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid241-> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,242-> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.243-244-```tsx245-import { create } from 'zustand'246-247-type PositionStore = [number, number]248-249-const usePositionStore = create<PositionStore>()(() => [0, 0])250-251-export default function MovingDot() {252- const [x, y] = usePositionStore()253- const setPosition: typeof usePositionStore.setState = (nextPosition) => {254- usePositionStore.setState(nextPosition, true)255- }256- const position = { x, y }257-258- return (259- <div260- onPointerMove={(e) => {261- setPosition([e.clientX, e.clientY])262- }}263- style={{264- position: 'relative',265- width: '100vw',266- height: '100vh',267- }}268- >269- <div270- style={{271- position: 'absolute',272- backgroundColor: 'red',273- borderRadius: '50%',274- transform: `translate(${position.x}px, ${position.y}px)`,275- left: -10,276- top: -10,277- width: 20,278- height: 20,279- }}280- />281- </div>282- )283-}284-```285-286-### Updating state with no store actions287-288-Defining actions at module level, external to the store have a few advantages like: it doesn't289-require a hook to call an action, and it facilitates code splitting.290-291-> [!NOTE]292-> The recommended way is to colocate actions and states within the store (let your actions be293-> located together with your state).294-295-```tsx296-import { create } from 'zustand'297-298-const usePositionStore = create<{299- x: number300- y: number301-}>()(() => ({ x: 0, y: 0 }))302-303-const setPosition: typeof usePositionStore.setState = (nextPosition) => {304- usePositionStore.setState(nextPosition)305-}306-307-export default function MovingDot() {308- const position = usePositionStore()309-310- return (311- <div312- style={{313- position: 'relative',314- width: '100vw',315- height: '100vh',316- }}317- >318- <div319- style={{320- position: 'absolute',321- backgroundColor: 'red',322- borderRadius: '50%',323- transform: `translate(${position.x}px, ${position.y}px)`,324- left: -10,325- top: -10,326- width: 20,327- height: 20,328- }}329- onMouseEnter={(event) => {330- const parent = event.currentTarget.parentElement331- const parentWidth = parent.clientWidth332- const parentHeight = parent.clientHeight333-334- setPosition({335- x: Math.ceil(Math.random() * parentWidth),336- y: Math.ceil(Math.random() * parentHeight),337- })338- }}339- />340- </div>341- )342-}343-```344-345-### Subscribing to state updates346-347-By subscribing to state updates, you register a callback that fires whenever the store's state348-updates. We can use `subscribe` for external state management.349-350-```tsx351-import { useEffect } from 'react'352-import { create } from 'zustand'353-354-type PositionStoreState = { position: { x: number; y: number } }355-356-type PositionStoreActions = {357- setPosition: (nextPosition: PositionStoreState['position']) => void358-}359-360-type PositionStore = PositionStoreState & PositionStoreActions361-362-const usePositionStore = create<PositionStore>()((set) => ({363- position: { x: 0, y: 0 },364- setPosition: (nextPosition) => set({ position: nextPosition }),365-}))366-367-export default function MovingDot() {368- const position = usePositionStore((state) => state.position)369- const setPosition = usePositionStore((state) => state.setPosition)370-371- useEffect(() => {372- const unsubscribePositionStore = usePositionStore.subscribe(373- ({ position }) => {374- console.log('new position', { position })375- },376- )377-378- return () => {379- unsubscribePositionStore()380- }381- }, [])382-383- return (384- <div385- style={{386- position: 'relative',387- width: '100vw',388- height: '100vh',389- }}390- >391- <div392- style={{393- position: 'absolute',394- backgroundColor: 'red',395- borderRadius: '50%',396- transform: `translate(${position.x}px, ${position.y}px)`,397- left: -10,398- top: -10,399- width: 20,400- height: 20,401- }}402- onMouseEnter={(event) => {403- const parent = event.currentTarget.parentElement404- const parentWidth = parent.clientWidth405- const parentHeight = parent.clientHeight406-407- setPosition({408- x: Math.ceil(Math.random() * parentWidth),409- y: Math.ceil(Math.random() * parentHeight),410- })411- }}412- />413- </div>414- )415-}416-```417-418-## Troubleshooting419-420-### I’ve updated the state, but the screen doesn’t update421-422-In the previous example, the `position` object is always created fresh from the current cursor423-position. But often, you will want to include existing data as a part of the new object you’re424-creating. For example, you may want to update only one field in a form, but keep the previous425-values for all other fields.426-427-These input fields don’t work because the `onChange` handlers mutate the state:428-429-```tsx430-import { create } from 'zustand'431-432-type PersonStoreState = {433- firstName: string434- lastName: string435- email: string436-}437-438-type PersonStoreActions = {439- setPerson: (nextPerson: Partial<PersonStoreState>) => void440-}441-442-type PersonStore = PersonStoreState & PersonStoreActions443-444-const usePersonStore = create<PersonStore>()((set) => ({445- firstName: 'Barbara',446- lastName: 'Hepworth',447- email: 'bhepworth@sculpture.com',448- setPerson: (nextPerson) => set(nextPerson),449-}))450-451-export default function Form() {452- const person = usePersonStore((state) => state)453- const setPerson = usePersonStore((state) => state.setPerson)454-455- function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {456- person.firstName = e.target.value457- }458-459- function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {460- person.lastName = e.target.value461- }462-463- function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {464- person.email = e.target.value465- }466-467- return (468- <>469- <label style={{ display: 'block' }}>470- First name:471- <input value={person.firstName} onChange={handleFirstNameChange} />472- </label>473- <label style={{ display: 'block' }}>474- Last name:475- <input value={person.lastName} onChange={handleLastNameChange} />476- </label>477- <label style={{ display: 'block' }}>478- Email:479- <input value={person.email} onChange={handleEmailChange} />480- </label>481- <p>482- {person.firstName} {person.lastName} ({person.email})483- </p>484- </>485- )486-}487-```488-489-For example, this line mutates the state from a past render:490-491-```tsx492-person.firstName = e.target.value493-```494-495-The reliable way to get the behavior you’re looking for is to create a new object and pass it to496-`setPerson`. But here you want to also copy the existing data into it because only one of the497-fields has changed:498-499-```ts500-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 by505-> default.506-507-Now the form works!508-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-512-```tsx {27,31,35}513-import { create } from 'zustand'514-515-type PersonStoreState = {516- person: { firstName: string; lastName: string; email: string }517-}518-519-type PersonStoreActions = {520- setPerson: (nextPerson: PersonStoreState['person']) => void521-}522-523-type PersonStore = PersonStoreState & PersonStoreActions524-525-const usePersonStore = create<PersonStore>()((set) => ({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() {535- const person = usePersonStore((state) => state.person)536- const setPerson = usePersonStore((state) => state.setPerson)537-538- function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {539- setPerson({ ...person, firstName: e.target.value })540- }541-542- function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {543- setPerson({ ...person, lastName: e.target.value })544- }545-546- function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {547- setPerson({ ...person, email: e.target.value })548- }549-550- return (551- <>552- <label style={{ display: 'block' }}>553- First name:554- <input value={person.firstName} onChange={handleFirstNameChange} />555- </label>556- <label style={{ display: 'block' }}>557- Last name:558- <input value={person.lastName} onChange={handleLastNameChange} />559- </label>560- <label style={{ display: 'block' }}>561- Email:562- <input value={person.email} onChange={handleEmailChange} />563- </label>564- <p>565- {person.firstName} {person.lastName} ({person.email})566- </p>567- </>568- )569-}570-```deleted:docs/apis/shallow.md-248 removed
1----2-title: shallow3-description: How compare simple data effectively4-nav: 275----6-7-`shallow` lets you run fast checks on simple data structures. It effectively identifies changes in8-**top-level** properties when you're working with data structures that don't have nested objects or9-arrays within them.10-11-> [!NOTE]12-> Shallow lets you perform quick comparisons, but keep its limitations in mind.13-14-```js15-const equal = shallow(a, b)16-```17-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- - [Comparing objects with different prototypes](#comparing-objects-with-different-prototypes)29-30-## Types31-32-### Signature33-34-```ts35-shallow<T>(a: T, b: T): boolean36-```37-38-## Reference39-40-### `shallow(a, b)`41-42-#### Parameters43-44-- `a`: The first value.45-- `b`: The second value.46-47-#### Returns48-49-`shallow` returns `true` when `a` and `b` are equal based on a shallow comparison of their50-**top-level** properties. Otherwise, it should return `false`.51-52-## Usage53-54-### Comparing Primitives55-56-When comparing primitive values like `string`s, `number`s, `boolean`s, and `BigInt`s, both57-`Object.is` and `shallow` function return `true` if the values are the same. This is because58-primitive values are compared by their actual value rather than by reference.59-60-```ts61-const stringLeft = 'John Doe'62-const stringRight = 'John Doe'63-64-Object.is(stringLeft, stringRight) // -> true65-shallow(stringLeft, stringRight) // -> true66-67-const numberLeft = 1068-const numberRight = 1069-70-Object.is(numberLeft, numberRight) // -> true71-shallow(numberLeft, numberRight) // -> true72-73-const booleanLeft = true74-const booleanRight = true75-76-Object.is(booleanLeft, booleanRight) // -> true77-shallow(booleanLeft, booleanRight) // -> true78-79-const bigIntLeft = 1n80-const bigIntRight = 1n81-82-Object.is(bigIntLeft, bigIntRight) // -> true83-shallow(bigIntLeft, bigIntRight) // -> true84-```85-86-### Comparing Objects87-88-When comparing objects, it's important to understand how `Object.is` and `shallow` function89-operate, as they handle comparisons differently.90-91-The `shallow` function returns `true` because shallow performs a shallow comparison of the objects.92-It checks if the top-level properties and their values are the same. In this case, the top-level93-properties (`firstName`, `lastName`, and `age`) and their values are identical between `objectLeft`94-and `objectRight`, so shallow considers them equal.95-96-```ts97-const objectLeft = {98- firstName: 'John',99- lastName: 'Doe',100- age: 30,101-}102-const objectRight = {103- firstName: 'John',104- lastName: 'Doe',105- age: 30,106-}107-108-Object.is(objectLeft, objectRight) // -> false109-shallow(objectLeft, objectRight) // -> true110-```111-112-### Comparing Sets113-114-When comparing sets, it's important to understand how `Object.is` and `shallow` function operate,115-as they handle comparisons differently.116-117-The `shallow` function returns `true` because shallow performs a shallow comparison of the sets. It118-checks if the top-level properties (in this case, the sets themselves) are the same. Since `setLeft`119-and `setRight` are both instances of the Set object and contain the same elements, shallow considers120-them equal.121-122-```ts123-const setLeft = new Set([1, 2, 3])124-const setRight = new Set([1, 2, 3])125-126-Object.is(setLeft, setRight) // -> false127-shallow(setLeft, setRight) // -> true128-```129-130-### Comparing Maps131-132-When comparing maps, it's important to understand how `Object.is` and `shallow` function operate, as133-they handle comparisons differently.134-135-The `shallow` returns `true` because shallow performs a shallow comparison of the maps. It checks if136-the top-level properties (in this case, the maps themselves) are the same. Since `mapLeft` and137-`mapRight` are both instances of the Map object and contain the same key-value pairs, shallow138-considers them equal.139-140-```ts141-const mapLeft = new Map([142- [1, 'one'],143- [2, 'two'],144- [3, 'three'],145-])146-const mapRight = new Map([147- [1, 'one'],148- [2, 'two'],149- [3, 'three'],150-])151-152-Object.is(mapLeft, mapRight) // -> false153-shallow(mapLeft, mapRight) // -> true154-```155-156-## Troubleshooting157-158-### Comparing objects returns `false` even if they are identical.159-160-The `shallow` function performs a shallow comparison. A shallow comparison checks if the top-level161-properties of two objects are equal. It does not check nested objects or deeply nested properties.162-In other words, it only compares the references of the properties.163-164-In the following example, the shallow function returns `false` because it compares only the165-top-level properties and their references. The address property in both objects is a nested object,166-and even though their contents are identical, their references are different. Consequently, shallow167-sees them as different, resulting in `false`.168-169-```ts170-const objectLeft = {171- firstName: 'John',172- lastName: 'Doe',173- age: 30,174- address: {175- street: 'Kulas Light',176- suite: 'Apt. 556',177- city: 'Gwenborough',178- zipcode: '92998-3874',179- geo: {180- lat: '-37.3159',181- lng: '81.1496',182- },183- },184-}185-const objectRight = {186- firstName: 'John',187- lastName: 'Doe',188- age: 30,189- address: {190- street: 'Kulas Light',191- suite: 'Apt. 556',192- city: 'Gwenborough',193- zipcode: '92998-3874',194- geo: {195- lat: '-37.3159',196- lng: '81.1496',197- },198- },199-}200-201-Object.is(objectLeft, objectRight) // -> false202-shallow(objectLeft, objectRight) // -> false203-```204-205-If we remove the `address` property, the shallow comparison would work as expected because all206-top-level properties would be primitive values or references to the same values:207-208-```ts209-const objectLeft = {210- firstName: 'John',211- lastName: 'Doe',212- age: 30,213-}214-const objectRight = {215- firstName: 'John',216- lastName: 'Doe',217- age: 30,218-}219-220-Object.is(objectLeft, objectRight) // -> false221-shallow(objectLeft, objectRight) // -> true222-```223-224-In this modified example, `objectLeft` and `objectRight` have the same top-level properties and225-primitive values. Since `shallow` function only compares the top-level properties, it will return226-`true` because the primitive values (`firstName`, `lastName`, and `age`) are identical in both227-objects.228-229-### Comparing objects with different prototypes230-231-The `shallow` function checks whether the two objects have the same prototype. If their prototypes232-are referentially different, shallow will return `false`. This comparison is done using:233-234-```ts235-Object.getPrototypeOf(a) === Object.getPrototypeOf(b)236-```237-238-> [!IMPORTANT]239-> Objects created with the object initializer (`{}`) or with `new Object()` inherit from240-> `Object.prototype` by default. However, objects created with `Object.create(proto)` inherit from241-> the proto you pass in—which may not be `Object.prototype.`242-243-```ts244-const a = Object.create({}) // -> prototype is `{}`245-const b = {} // -> prototype is `Object.prototype`246-247-shallow(a, b) // -> false248-```deleted:docs/getting-started/comparison.md-483 removed
1----2-title: Comparison3-description: How Zustand stacks up against similar libraries4-nav: 15----6-7-Zustand is one of many state management libraries for React.8-On this page we will discuss Zustand9-in comparison to some of these libraries,10-including Redux, Valtio, Jotai, and Recoil.11-12-Each library has its own strengths and weaknesses,13-and we will compare key differences and similarities between each.14-15-## Redux16-17-### State Model (vs Redux)18-19-Conceptually, Zustand and Redux are quite similar,20-both are based on an immutable state model.21-However, Redux requires your app to be wrapped22-in context providers; Zustand does not.23-24-**Zustand**25-26-```ts27-import { create } from 'zustand'28-29-type State = {30- count: number31-}32-33-type Actions = {34- increment: (qty: number) => void35- decrement: (qty: number) => void36-}37-38-const useCountStore = create<State & Actions>((set) => ({39- count: 0,40- increment: (qty: number) => set((state) => ({ count: state.count + qty })),41- decrement: (qty: number) => set((state) => ({ count: state.count - qty })),42-}))43-```44-45-```ts46-import { create } from 'zustand'47-48-type State = {49- count: number50-}51-52-type Action = {53- type: 'increment' | 'decrement'54- qty: number55-}56-57-type Actions = {58- dispatch: (action: Action) => void59-}60-61-const countReducer = (state: State, action: Action) => {62- switch (action.type) {63- case 'increment':64- return { count: state.count + action.qty }65- case 'decrement':66- return { count: state.count - action.qty }67- default:68- return state69- }70-}71-72-const useCountStore = create<State & Actions>((set) => ({73- count: 0,74- dispatch: (action: Action) => set((state) => countReducer(state, action)),75-}))76-```77-78-**Redux**79-80-```ts81-import { createStore } from 'redux'82-import { useSelector, useDispatch } from 'react-redux'83-84-type State = {85- count: number86-}87-88-type Action = {89- type: 'increment' | 'decrement'90- qty: number91-}92-93-const countReducer = (state: State, action: Action) => {94- switch (action.type) {95- case 'increment':96- return { count: state.count + action.qty }97- case 'decrement':98- return { count: state.count - action.qty }99- default:100- return state101- }102-}103-104-const countStore = createStore(countReducer)105-```106-107-```ts108-import { createSlice, configureStore } from '@reduxjs/toolkit'109-110-const countSlice = createSlice({111- name: 'count',112- initialState: { value: 0 },113- reducers: {114- incremented: (state, qty: number) => {115- // Redux Toolkit does not mutate the state, it uses the Immer library116- // behind scenes, allowing us to have something called "draft state".117- state.value += qty118- },119- decremented: (state, qty: number) => {120- state.value -= qty121- },122- },123-})124-125-const countStore = configureStore({ reducer: countSlice.reducer })126-```127-128-### Render Optimization (vs Redux)129-130-When it comes to render optimizations within your app,131-there are no major differences in approach between Zustand and Redux.132-In both libraries it is recommended133-that you manually apply render optimizations by using selectors.134-135-**Zustand**136-137-```ts138-import { create } from 'zustand'139-140-type State = {141- count: number142-}143-144-type Actions = {145- increment: (qty: number) => void146- decrement: (qty: number) => void147-}148-149-const useCountStore = create<State & Actions>((set) => ({150- count: 0,151- increment: (qty: number) => set((state) => ({ count: state.count + qty })),152- decrement: (qty: number) => set((state) => ({ count: state.count - qty })),153-}))154-155-const Component = () => {156- const count = useCountStore((state) => state.count)157- const increment = useCountStore((state) => state.increment)158- const decrement = useCountStore((state) => state.decrement)159- // ...160-}161-```162-163-**Redux**164-165-```ts166-import { createStore } from 'redux'167-import { useSelector, useDispatch } from 'react-redux'168-169-type State = {170- count: number171-}172-173-type Action = {174- type: 'increment' | 'decrement'175- qty: number176-}177-178-const countReducer = (state: State, action: Action) => {179- switch (action.type) {180- case 'increment':181- return { count: state.count + action.qty }182- case 'decrement':183- return { count: state.count - action.qty }184- default:185- return state186- }187-}188-189-const countStore = createStore(countReducer)190-191-const Component = () => {192- const count = useSelector((state) => state.count)193- const dispatch = useDispatch()194- // ...195-}196-```197-198-```ts199-import { useSelector } from 'react-redux'200-import type { TypedUseSelectorHook } from 'react-redux'201-import { createSlice, configureStore } from '@reduxjs/toolkit'202-203-const countSlice = createSlice({204- name: 'count',205- initialState: { value: 0 },206- reducers: {207- incremented: (state, qty: number) => {208- // Redux Toolkit does not mutate the state, it uses the Immer library209- // behind scenes, allowing us to have something called "draft state".210- state.value += qty211- },212- decremented: (state, qty: number) => {213- state.value -= qty214- },215- },216-})217-218-const countStore = configureStore({ reducer: countSlice.reducer })219-220-const useAppSelector: TypedUseSelectorHook<typeof countStore.getState> =221- useSelector222-223-const useAppDispatch: () => typeof countStore.dispatch = useDispatch224-225-const Component = () => {226- const count = useAppSelector((state) => state.count.value)227- const dispatch = useAppDispatch()228- // ...229-}230-```231-232-## Valtio233-234-### State Model (vs Valtio)235-236-Zustand and Valtio approach state management237-in a fundamentally different way.238-Zustand is based on the **immutable** state model,239-while Valtio is based on the **mutable** state model.240-241-**Zustand**242-243-```ts244-import { create } from 'zustand'245-246-type State = {247- obj: { count: number }248-}249-250-const store = create<State>(() => ({ obj: { count: 0 } }))251-252-store.setState((prev) => ({ obj: { count: prev.obj.count + 1 } }))253-```254-255-**Valtio**256-257-```ts258-import { proxy } from 'valtio'259-260-const state = proxy({ obj: { count: 0 } })261-262-state.obj.count += 1263-```264-265-### Render Optimization (vs Valtio)266-267-The other difference between Zustand and Valtio268-is Valtio makes render optimizations through property access.269-However, with Zustand, it is recommended that270-you manually apply render optimizations by using selectors.271-272-**Zustand**273-274-```ts275-import { create } from 'zustand'276-277-type State = {278- count: number279-}280-281-const useCountStore = create<State>(() => ({282- count: 0,283-}))284-285-const Component = () => {286- const count = useCountStore((state) => state.count)287- // ...288-}289-```290-291-**Valtio**292-293-```ts294-import { proxy, useSnapshot } from 'valtio'295-296-const state = proxy({297- count: 0,298-})299-300-const Component = () => {301- const { count } = useSnapshot(state)302- // ...303-}304-```305-306-## Jotai307-308-### State Model (vs Jotai)309-310-There is one major difference between Zustand and Jotai.311-Zustand is a single store,312-while Jotai consists of primitive atoms that can be composed together.313-314-**Zustand**315-316-```ts317-import { create } from 'zustand'318-319-type State = {320- count: number321-}322-323-type Actions = {324- updateCount: (325- countCallback: (count: State['count']) => State['count'],326- ) => void327-}328-329-const useCountStore = create<State & Actions>((set) => ({330- count: 0,331- updateCount: (countCallback) =>332- set((state) => ({ count: countCallback(state.count) })),333-}))334-```335-336-**Jotai**337-338-```ts339-import { atom } from 'jotai'340-341-const countAtom = atom<number>(0)342-```343-344-### Render Optimization (vs Jotai)345-346-Jotai achieves render optimizations through atom dependency.347-However, with Zustand it is recommended that348-you manually apply render optimizations by using selectors.349-350-**Zustand**351-352-```ts353-import { create } from 'zustand'354-355-type State = {356- count: number357-}358-359-type Actions = {360- updateCount: (361- countCallback: (count: State['count']) => State['count'],362- ) => void363-}364-365-const useCountStore = create<State & Actions>((set) => ({366- count: 0,367- updateCount: (countCallback) =>368- set((state) => ({ count: countCallback(state.count) })),369-}))370-371-const Component = () => {372- const count = useCountStore((state) => state.count)373- const updateCount = useCountStore((state) => state.updateCount)374- // ...375-}376-```377-378-**Jotai**379-380-```ts381-import { atom, useAtom } from 'jotai'382-383-const countAtom = atom<number>(0)384-385-const Component = () => {386- const [count, updateCount] = useAtom(countAtom)387- // ...388-}389-```390-391-## Recoil392-393-### State Model (vs Recoil)394-395-The difference between Zustand and Recoil396-is similar to that between Zustand and Jotai.397-Recoil depends on atom string keys398-instead of atom object referential identities.399-Additionally, Recoil needs to wrap your app in a context provider.400-401-**Zustand**402-403-```ts404-import { create } from 'zustand'405-406-type State = {407- count: number408-}409-410-type Actions = {411- setCount: (countCallback: (count: State['count']) => State['count']) => void412-}413-414-const useCountStore = create<State & Actions>((set) => ({415- count: 0,416- setCount: (countCallback) =>417- set((state) => ({ count: countCallback(state.count) })),418-}))419-```420-421-**Recoil**422-423-```ts424-import { atom } from 'recoil'425-426-const count = atom({427- key: 'count',428- default: 0,429-})430-```431-432-### Render Optimization (vs Recoil)433-434-Similar to previous optimization comparisons,435-Recoil makes render optimizations through atom dependency.436-Whereas with Zustand, it is recommended that437-you manually apply render optimizations by using selectors.438-439-**Zustand**440-441-```ts442-import { create } from 'zustand'443-444-type State = {445- count: number446-}447-448-type Actions = {449- setCount: (countCallback: (count: State['count']) => State['count']) => void450-}451-452-const useCountStore = create<State & Actions>((set) => ({453- count: 0,454- setCount: (countCallback) =>455- set((state) => ({ count: countCallback(state.count) })),456-}))457-458-const Component = () => {459- const count = useCountStore((state) => state.count)460- const setCount = useCountStore((state) => state.setCount)461- // ...462-}463-```464-465-**Recoil**466-467-```ts468-import { atom, useRecoilState } from 'recoil'469-470-const countAtom = atom({471- key: 'count',472- default: 0,473-})474-475-const Component = () => {476- const [count, setCount] = useRecoilState(countAtom)477- // ...478-}479-```480-481-## Npm Downloads Trend482-483-- [Npm Downloads Trend of State Management Libraries for React](https://npm-stat.com/charts.html?package=zustand&package=jotai&package=valtio&package=%40reduxjs%2Ftoolkit&package=recoil)deleted:docs/getting-started/introduction.md-72 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172---title: Introductiondescription: How to use Zustandnav: 0---
<div class="flex justify-center mb-4"> <img src="../bear.jpg" alt="Logo Zustand" /></div>
A small, fast, and scalable bearbones state management solution.Zustand has a comfy API based on hooks.It isn't boilerplatey or opinionated,but has enough convention to be explicit and flux-like.
Don't disregard it because it's cute, it has claws!Lots of time was spent to deal with common pitfalls,like the dreaded [zombie child problem],[React concurrency], and [context loss]between mixed renderers.It may be the one state manager in the React space that gets all of these right.
You can try a live demo [here](https://codesandbox.io/s/dazzling-moon-itop4).
[zombie child problem]: https://react-redux.js.org/api/hooks#stale-props-and-zombie-children[react concurrency]: https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md[context loss]: https://github.com/facebook/react/issues/13332
## Installation
Zustand is available as a package on NPM for use:
```bash# NPMnpm install zustand# Or, use any package manager of your choice.```
## First create a store
Your store is a hook!You can put anything in it: primitives, objects, functions.The `set` function _merges_ state.
```jsimport { create } from 'zustand'
const useBear = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), updateBears: (newBears) => set({ bears: newBears }),}))```
## Then bind your components, and that's it!
You can use the hook anywhere, without the need of providers.Select your state and the consuming componentwill re-render when that state changes.
```jsxfunction BearCounter() { const bears = useBear((state) => state.bears) return <h1>{bears} bears around here...</h1>}
function Controls() { const increasePopulation = useBear((state) => state.increasePopulation) return <button onClick={increasePopulation}>one up</button>}```deleted:docs/guides/advanced-typescript.md-542 removed
1----2-title: Advanced TypeScript Guide3-nav: 74----5-6-## Basic usage7-8-The difference when using TypeScript is that instead of writing `create(...)`, you have to write `create<T>()(...)` (notice the extra parentheses `()` too along with the type parameter) where `T` is the type of the state to annotate it. For example:9-10-```ts11-import { create } from 'zustand'12-13-interface BearState {14- bears: number15- increase: (by: number) => void16-}17-18-const useBearStore = create<BearState>()((set) => ({19- bears: 0,20- increase: (by) => set((state) => ({ bears: state.bears + by })),21-}))22-```23-24-<details>25- <summary>Why can't we simply infer the type from the initial state?</summary>26-27- <br/>28-29-**TLDR**: Because state generic `T` is invariant.30-31-Consider this minimal version `create`:32-33-```ts34-declare const create: <T>(f: (get: () => T) => T) => T35-36-const x = create((get) => ({37- foo: 0,38- bar: () => get(),39-}))40-// `x` is inferred as `unknown` instead of41-// interface X {42-// foo: number,43-// bar: () => X44-// }45-```46-47-Here, if you look at the type of `f` in `create`, i.e. `(get: () => T) => T`, it "gives" `T` via return (making it covariant), but it also "takes" `T` via `get` (making it contravariant). "So where does `T` come from?" TypeScript wonders. It's like that chicken or egg problem. At the end TypeScript, gives up and infers `T` as `unknown`.48-49-So, as long as the generic to be inferred is invariant (i.e. both covariant and contravariant), TypeScript will be unable to infer it. Another simple example would be this:50-51-```ts52-const createFoo = {} as <T>(f: (t: T) => T) => T53-const x = createFoo((_) => 'hello')54-```55-56-Here again, `x` is `unknown` instead of `string`.57-58- <details>59- <summary>More about the inference (just for the people curious and interested in TypeScript)</summary>60-61-In some sense this inference failure is not a problem because a value of type `<T>(f: (t: T) => T) => T` cannot be written. That is to say you can't write the real runtime implementation of `createFoo`. Let's try it:62-63-```js64-const createFoo = (f) => f(/* ? */)65-```66-67-`createFoo` needs to return the return value of `f`. And to do that we first have to call `f`. And to call it we have to pass a value of type `T`. And to pass a value of type `T` we first have to produce it. But how can we produce a value of type `T` when we don't even know what `T` is? The only way to produce a value of type `T` is to call `f`, but then to call `f` itself we need a value of type `T`. So you see it's impossible to actually write `createFoo`.68-69-So what we're saying is, the inference failure in case of `createFoo` is not really a problem because it's impossible to implement `createFoo`. But what about the inference failure in case of `create`? That also is not really a problem because it's impossible to implement `create` too. Wait a minute, if it's impossible to implement `create` then how does Zustand implement it? The answer is, it doesn't.70-71-Zustand lies that it implemented `create`'s type, it implemented only the most part of it. Here's a simple proof by showing unsoundness. Consider the following code:72-73-```ts74-import { create } from 'zustand'75-76-const useBoundStore = create<{ foo: number }>()((_, get) => ({77- foo: get().foo,78-}))79-```80-81-This code compiles. But if we run it, we'll get an exception: "Uncaught TypeError: Cannot read properties of undefined (reading 'foo')". This is because `get` would return `undefined` before the initial state is created (hence you shouldn't call `get` when creating the initial state). The types promise that `get` will never return `undefined` but it does initially, which means Zustand failed to implement it.82-83-And of course Zustand failed because it's impossible to implement `create` the way types promise (in the same way it's impossible to implement `createFoo`). In other words we don't have a type to express the actual `create` we have implemented. We can't type `get` as `() => T | undefined` because it would cause inconvenience and it still won't be correct as `get` is indeed `() => T` eventually, just if called synchronously it would be `() => undefined`. What we need is some kind of TypeScript feature that allows us to type `get` as `(() => T) & WhenSync<() => undefined>`, which of course is extremely far-fetched.84-85-So we have two problems: lack of inference and unsoundness. Lack of inference can be solved if TypeScript can improve its inference for invariants. And unsoundness can be solved if TypeScript introduces something like `WhenSync`. To work around lack of inference we manually annotate the state type. And we can't work around unsoundness, but it's not a big deal because it's not much, calling `get` synchronously anyway doesn't make sense.86-87-</details>88-89-</details>90-91-<details>92- <summary>Why the currying `()(...)`?</summary>93-94- <br/>95-96-**TLDR**: It is a workaround for [microsoft/TypeScript#10571](https://github.com/microsoft/TypeScript/issues/10571).97-98-Imagine you have a scenario like this:99-100-```ts101-declare const withError: <T, E>(102- p: Promise<T>,103-) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>104-declare const doSomething: () => Promise<string>105-106-const main = async () => {107- let [error, value] = await withError(doSomething())108-}109-```110-111-Here, `T` is inferred to be a `string` and `E` is inferred to be `unknown`. You might want to annotate `E` as `Foo`, because you are certain of the shape of error `doSomething()` would throw. However, you can't do that. You can either pass all generics or none. Along with annotating `E` as `Foo`, you will also have to annotate `T` as `string` even though it gets inferred anyway. The solution is to make a curried version of `withError` that does nothing at runtime. Its purpose is to just allow you annotate `E`.112-113-```ts114-declare const withError: {115- <E>(): <T>(116- p: Promise<T>,117- ) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>118- <T, E>(119- p: Promise<T>,120- ): Promise<[error: undefined, value: T] | [error: E, value: undefined]>121-}122-declare const doSomething: () => Promise<string>123-interface Foo {124- bar: string125-}126-127-const main = async () => {128- let [error, value] = await withError<Foo>()(doSomething())129-}130-```131-132-This way, `T` gets inferred and you get to annotate `E`. Zustand has the same use case when we want to annotate the state (the first type parameter) but allow other parameters to get inferred.133-134-</details>135-136-Alternatively, you can also use `combine`, which infers the state so that you do not need to type it.137-138-```ts139-import { create } from 'zustand'140-import { combine } from 'zustand/middleware'141-142-const useBearStore = create(143- combine({ bears: 0 }, (set) => ({144- increase: (by: number) => set((state) => ({ bears: state.bears + by })),145- })),146-)147-```148-149-<details>150- <summary>Be a little careful</summary>151-152- <br/>153-154-We achieve the inference by lying a little in the types of `set`, `get`, and `store` that you receive as parameters. The lie is that they're typed as if the state is the first parameter, when in fact the state is the shallow-merge (`{ ...a, ...b }`) of both first parameter and the second parameter's return. For example, `get` from the second parameter has type `() => { bears: number }` and that is a lie as it should be `() => { bears: number, increase: (by: number) => void }`. And `useBearStore` still has the correct type; for example, `useBearStore.getState` is typed as `() => { bears: number, increase: (by: number) => void }`.155-156-It isn't really a lie because `{ bears: number }` is still a subtype of `{ bears: number, increase: (by: number) => void }`. Therefore, there will be no problem in most cases. You should just be careful while using replace. For example, `set({ bears: 0 }, true)` would compile but will be unsound as it will delete the `increase` function. Another instance where you should be careful is if you use `Object.keys`. `Object.keys(get())` will return `["bears", "increase"]` and not `["bears"]`. The return type of `get` can make you fall for these mistakes.157-158-`combine` trades off a little type-safety for the convenience of not having to write a type for state. Hence, you should use `combine` accordingly. It is fine in most cases and you can use it conveniently.159-160-</details>161-162-Note that we don't use the curried version when using `combine` because `combine` "creates" the state. When using a middleware that creates the state, it isn't necessary to use the curried version because the state now can be inferred. Another middleware that creates state is `redux`. So when using `combine`, `redux`, or any other custom middleware that creates the state, we don't recommend using the curried version.163-164-If you want to infer state type also outside of state declaration, you can use the `ExtractState` type helper:165-166-```ts167-import { create, ExtractState } from 'zustand'168-import { combine } from 'zustand/middleware'169-170-type BearState = ExtractState<typeof useBearStore>171-172-const useBearStore = create(173- combine({ bears: 0 }, (set) => ({174- increase: (by: number) => set((state) => ({ bears: state.bears + by })),175- })),176-)177-```178-179-## Using middlewares180-181-You do not have to do anything special to use middlewares in TypeScript.182-183-```ts184-import { create } from 'zustand'185-import { devtools, persist } from 'zustand/middleware'186-187-interface BearState {188- bears: number189- increase: (by: number) => void190-}191-192-const useBearStore = create<BearState>()(193- devtools(194- persist(195- (set) => ({196- bears: 0,197- increase: (by) => set((state) => ({ bears: state.bears + by })),198- }),199- { name: 'bearStore' },200- ),201- ),202-)203-```204-205-Just make sure you are using them immediately inside `create` so as to make the contextual inference work. Doing something even remotely fancy like the following `myMiddlewares` would require more advanced types.206-207-```ts208-import { create } from 'zustand'209-import { devtools, persist } from 'zustand/middleware'210-211-const myMiddlewares = (f) => devtools(persist(f, { name: 'bearStore' }))212-213-interface BearState {214- bears: number215- increase: (by: number) => void216-}217-218-const useBearStore = create<BearState>()(219- myMiddlewares((set) => ({220- bears: 0,221- increase: (by) => set((state) => ({ bears: state.bears + by })),222- })),223-)224-```225-226-Also, we recommend using `devtools` middleware as last as possible. For example, when you use it with `immer` as a middleware, it should be `devtools(immer(...))` and not `immer(devtools(...))`. This is because`devtools` mutates the `setState` and adds a type parameter on it, which could get lost if other middlewares (like `immer`) also mutate `setState` before `devtools`. Hence using `devtools` at the end makes sure that no middlewares mutate `setState` before it.227-228-## Authoring middlewares and advanced usage229-230-Imagine you had to write this hypothetical middleware.231-232-```ts233-import { create } from 'zustand'234-235-const foo = (f, bar) => (set, get, store) => {236- store.foo = bar237- return f(set, get, store)238-}239-240-const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))241-console.log(useBearStore.foo.toUpperCase())242-```243-244-Zustand middlewares can mutate the store. But how could we possibly encode the mutation on the type-level? That is to say how could we type `foo` so that this code compiles?245-246-For a usual statically typed language, this is impossible. But thanks to TypeScript, Zustand has something called a "higher-kinded mutator" that makes this possible. If you are dealing with complex type problems, like typing a middleware or using the `StateCreator` type, you will have to understand this implementation detail. For this, you can [check out #710](https://github.com/pmndrs/zustand/issues/710).247-248-If you are eager to know what the answer is to this particular problem then you can [see it here](#middleware-that-changes-the-store-type).249-250-### Handling Dynamic `replace` Flag251-252-If the value of the `replace` flag is not known at compile time and is determined dynamically, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:253-254-```ts255-const replaceFlag = Math.random() > 0.5256-const args = [{ bears: 5 }, replaceFlag] as Parameters<257- typeof useBearStore.setState258->259-store.setState(...args)260-```261-262-#### Example with `as Parameters` Workaround263-264-```ts265-import { create } from 'zustand'266-267-interface BearState {268- bears: number269- increase: (by: number) => void270-}271-272-const useBearStore = create<BearState>()((set) => ({273- bears: 0,274- increase: (by) => set((state) => ({ bears: state.bears + by })),275-}))276-277-const replaceFlag = Math.random() > 0.5278-const args = [{ bears: 5 }, replaceFlag] as Parameters<279- typeof useBearStore.setState280->281-useBearStore.setState(...args) // Using the workaround282-```283-284-By following this approach, you can ensure that your code handles dynamic `replace` flags without encountering type issues.285-286-## Common recipes287-288-### Middleware that doesn't change the store type289-290-```ts291-import { create, StateCreator, StoreMutatorIdentifier } from 'zustand'292-293-type Logger = <294- T,295- Mps extends [StoreMutatorIdentifier, unknown][] = [],296- Mcs extends [StoreMutatorIdentifier, unknown][] = [],297->(298- f: StateCreator<T, Mps, Mcs>,299- name?: string,300-) => StateCreator<T, Mps, Mcs>301-302-type LoggerImpl = <T>(303- f: StateCreator<T, [], []>,304- name?: string,305-) => StateCreator<T, [], []>306-307-const loggerImpl: LoggerImpl = (f, name) => (set, get, store) => {308- const loggedSet: typeof set = (...a) => {309- set(...(a as Parameters<typeof set>))310- console.log(...(name ? [`${name}:`] : []), get())311- }312- const setState = store.setState313- store.setState = (...a) => {314- setState(...(a as Parameters<typeof setState>))315- console.log(...(name ? [`${name}:`] : []), store.getState())316- }317-318- return f(loggedSet, get, store)319-}320-321-export const logger = loggerImpl as unknown as Logger322-323-// ---324-325-const useBearStore = create<BearState>()(326- logger(327- (set) => ({328- bears: 0,329- increase: (by) => set((state) => ({ bears: state.bears + by })),330- }),331- 'bear-store',332- ),333-)334-```335-336-### Middleware that changes the store type337-338-```ts339-import {340- create,341- StateCreator,342- StoreMutatorIdentifier,343- Mutate,344- StoreApi,345-} from 'zustand'346-347-type Foo = <348- T,349- A,350- Mps extends [StoreMutatorIdentifier, unknown][] = [],351- Mcs extends [StoreMutatorIdentifier, unknown][] = [],352->(353- f: StateCreator<T, [...Mps, ['foo', A]], Mcs>,354- bar: A,355-) => StateCreator<T, Mps, [['foo', A], ...Mcs]>356-357-declare module 'zustand' {358- interface StoreMutators<S, A> {359- foo: Write<Cast<S, object>, { foo: A }>360- }361-}362-363-type FooImpl = <T, A>(364- f: StateCreator<T, [], []>,365- bar: A,366-) => StateCreator<T, [], []>367-368-const fooImpl: FooImpl = (f, bar) => (set, get, _store) => {369- type T = ReturnType<typeof f>370- type A = typeof bar371-372- const store = _store as Mutate<StoreApi<T>, [['foo', A]]>373- store.foo = bar374- return f(set, get, _store)375-}376-377-export const foo = fooImpl as unknown as Foo378-379-type Write<T extends object, U extends object> = Omit<T, keyof U> & U380-381-type Cast<T, U> = T extends U ? T : U382-383-// ---384-385-const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))386-console.log(useBearStore.foo.toUpperCase())387-```388-389-### `create` without curried workaround390-391-The recommended way to use `create` is using the curried workaround like so: `create<T>()(...)`. This is because it enables you to infer the store type. But if for some reason you do not want to use the workaround, you can pass the type parameters like the following. Note that in some cases, this acts as an assertion instead of annotation, so we don't recommend it.392-393-```ts394-import { create } from "zustand"395-396-interface BearState {397- bears: number398- increase: (by: number) => void399-}400-401-const useBearStore = create<402- BearState,403- [404- ['zustand/persist', BearState],405- ['zustand/devtools', never]406- ]407->(devtools(persist((set) => ({408- bears: 0,409- increase: (by) => set((state) => ({ bears: state.bears + by })),410-}), { name: 'bearStore' }))411-```412-413-### Slices pattern414-415-```ts416-import { create, StateCreator } from 'zustand'417-418-interface BearSlice {419- bears: number420- addBear: () => void421- eatFish: () => void422-}423-424-interface FishSlice {425- fishes: number426- addFish: () => void427-}428-429-interface SharedSlice {430- addBoth: () => void431- getBoth: () => number432-}433-434-const createBearSlice: StateCreator<435- BearSlice & FishSlice,436- [],437- [],438- BearSlice439-> = (set) => ({440- bears: 0,441- addBear: () => set((state) => ({ bears: state.bears + 1 })),442- eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),443-})444-445-const createFishSlice: StateCreator<446- BearSlice & FishSlice,447- [],448- [],449- FishSlice450-> = (set) => ({451- fishes: 0,452- addFish: () => set((state) => ({ fishes: state.fishes + 1 })),453-})454-455-const createSharedSlice: StateCreator<456- BearSlice & FishSlice,457- [],458- [],459- SharedSlice460-> = (set, get) => ({461- addBoth: () => {462- // you can reuse previous methods463- get().addBear()464- get().addFish()465- // or do them from scratch466- // set((state) => ({ bears: state.bears + 1, fishes: state.fishes + 1 })467- },468- getBoth: () => get().bears + get().fishes,469-})470-471-const useBoundStore = create<BearSlice & FishSlice & SharedSlice>()((...a) => ({472- ...createBearSlice(...a),473- ...createFishSlice(...a),474- ...createSharedSlice(...a),475-}))476-```477-478-A detailed explanation on the slices pattern can be found [here](./slices-pattern.md).479-480-If you have some middlewares then replace `StateCreator<MyState, [], [], MySlice>` with `StateCreator<MyState, Mutators, [], MySlice>`. For example, if you are using `devtools` then it will be `StateCreator<MyState, [["zustand/devtools", never]], [], MySlice>`. See the ["Middlewares and their mutators reference"](#middlewares-and-their-mutators-reference) section for a list of all mutators.481-482-### Bounded `useStore` hook for vanilla stores483-484-```ts485-import { useStore } from 'zustand'486-import { createStore } from 'zustand/vanilla'487-488-interface BearState {489- bears: number490- increase: (by: number) => void491-}492-493-const bearStore = createStore<BearState>()((set) => ({494- bears: 0,495- increase: (by) => set((state) => ({ bears: state.bears + by })),496-}))497-498-function useBearStore(): BearState499-function useBearStore<T>(selector: (state: BearState) => T): T500-function useBearStore<T>(selector?: (state: BearState) => T) {501- return useStore(bearStore, selector!)502-}503-```504-505-You can also make an abstract `createBoundedUseStore` function if you need to create bounded `useStore` hooks often and want to DRY things up...506-507-```ts508-import { useStore, StoreApi } from 'zustand'509-import { createStore } from 'zustand/vanilla'510-511-interface BearState {512- bears: number513- increase: (by: number) => void514-}515-516-const bearStore = createStore<BearState>()((set) => ({517- bears: 0,518- increase: (by) => set((state) => ({ bears: state.bears + by })),519-}))520-521-const createBoundedUseStore = ((store) => (selector) =>522- useStore(store, selector)) as <S extends StoreApi<unknown>>(523- store: S,524-) => {525- (): ExtractState<S>526- <T>(selector: (state: ExtractState<S>) => T): T527-}528-529-type ExtractState<S> = S extends { getState: () => infer X } ? X : never530-531-const useBearStore = createBoundedUseStore(bearStore)532-```533-534-## Middlewares and their mutators reference535-536-- `devtools` — `["zustand/devtools", never]`537-- `persist` — `["zustand/persist", YourPersistedState]`<br/>538- `YourPersistedState` is the type of state you are going to persist, ie the return type of `options.partialize`, if you're not passing `partialize` options the `YourPersistedState` becomes `Partial<YourState>`. Also [sometimes](https://github.com/pmndrs/zustand/issues/980#issuecomment-1162289836) passing actual `PersistedState` won't work. In those cases, try passing `unknown`.539-- `immer` — `["zustand/immer", never]`540-- `subscribeWithSelector` — `["zustand/subscribeWithSelector", never]`541-- `redux` — `["zustand/redux", YourAction]`542-- `combine` — no mutator as `combine` does not mutate the storedeleted:docs/guides/auto-generating-selectors.md-134 removed
1----2-title: Auto Generating Selectors3-nav: 54----5-6-We recommend using selectors when using either the properties or actions from the store. You can access values from the store like so:7-8-```typescript9-const bears = useBearStore((state) => state.bears)10-```11-12-However, writing these could be tedious. If that is the case for you, you can auto-generate your selectors.13-14-## Create the following function: `createSelectors`15-16-```typescript17-import { StoreApi, UseBoundStore } from 'zustand'18-19-type WithSelectors<S> = S extends { getState: () => infer T }20- ? S & { use: { [K in keyof T]: () => T[K] } }21- : never22-23-const createSelectors = <S extends UseBoundStore<StoreApi<object>>>(24- _store: S,25-) => {26- const store = _store as WithSelectors<typeof _store>27- store.use = {}28- for (const k of Object.keys(store.getState())) {29- ;(store.use as any)[k] = () => store((s) => s[k as keyof typeof s])30- }31-32- return store33-}34-```35-36-If you have a store like this:37-38-```typescript39-interface BearState {40- bears: number41- increase: (by: number) => void42- increment: () => void43-}44-45-const useBearStoreBase = create<BearState>()((set) => ({46- bears: 0,47- increase: (by) => set((state) => ({ bears: state.bears + by })),48- increment: () => set((state) => ({ bears: state.bears + 1 })),49-}))50-```51-52-Apply that function to your store:53-54-```typescript55-const useBearStore = createSelectors(useBearStoreBase)56-```57-58-Now the selectors are auto generated and you can access them directly:59-60-```typescript61-// get the property62-const bears = useBearStore.use.bears()63-64-// get the action65-const increment = useBearStore.use.increment()66-```67-68-## Vanilla Store69-70-If you are using a vanilla store, use the following `createSelectors` function:71-72-```typescript73-import { StoreApi, useStore } from 'zustand'74-75-type WithSelectors<S> = S extends { getState: () => infer T }76- ? S & { use: { [K in keyof T]: () => T[K] } }77- : never78-79-const createSelectors = <S extends StoreApi<object>>(_store: S) => {80- const store = _store as WithSelectors<typeof _store>81- store.use = {}82- for (const k of Object.keys(store.getState())) {83- ;(store.use as any)[k] = () =>84- useStore(_store, (s) => s[k as keyof typeof s])85- }86-87- return store88-}89-```90-91-The usage is the same as a React store. If you have a store like this:92-93-```typescript94-import { createStore } from 'zustand'95-96-interface BearState {97- bears: number98- increase: (by: number) => void99- increment: () => void100-}101-102-const store = createStore<BearState>()((set) => ({103- bears: 0,104- increase: (by) => set((state) => ({ bears: state.bears + by })),105- increment: () => set((state) => ({ bears: state.bears + 1 })),106-}))107-```108-109-Apply that function to your store:110-111-```typescript112-const useBearStore = createSelectors(store)113-```114-115-Now the selectors are auto generated and you can access them directly:116-117-```typescript118-// get the property119-const bears = useBearStore.use.bears()120-121-// get the action122-const increment = useBearStore.use.increment()123-```124-125-## Live Demo126-127-For a working example of this, see the [Code Sandbox](https://codesandbox.io/s/zustand-auto-generate-selectors-forked-rl8v5e?file=/src/selectors.ts).128-129-## Third-party Libraries130-131-- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook)132-- [react-hooks-global-state](https://github.com/dai-shi/react-hooks-global-state)133-- [zustood](https://github.com/udecode/zustood)134-- [@davstack/store](https://github.com/DawidWraga/davstack)deleted:docs/guides/beginner-typescript.md-378 removed
1----2-title: Beginner TypeScript Guide3-nav: 74----5-6-Zustand is a lightweight state manager, particularly used with React. Zustand avoids reducers, context, and boilerplate.7-Paired with TypeScript, you get a strongly typed store-state, actions, and selectors-with autocomplete and compile-time safety.8-9-In this basic guide we’ll cover:10-11-- Creating a typed store (state + actions)12-- Using the store in React components with type safety13-- Resetting the store safely with types14-- Extracting and reusing Store type (for props, tests, and utilities)15-- Composing multiple selectors and building derived state (with type inference and without extra re-renders)16-- Middlewares with TypeScript support (`combine`, `devtools`, `persist`)17-- Async actions with typed API responses18-- Working with `createWithEqualityFn` (enhanced `create` store function)19-- Structuring and coordinating multiple stores20-21-### Creating a Store with State & Actions22-23-Here we describe state and actions using an Typescript interface. The `<BearState>` generic forces the store to match this shape.24-This means if you forget a field or use the wrong type, TypeScript will complain. Unlike plain JS, this guarantees type-safe state management.25-The `create` function uses the curried form, which results in a store of type `UseBoundStore<StoreApi<BearState>>`.26-27-```ts28-// store.ts29-import { create } from 'zustand'30-31-// Define types for state & actions32-interface BearState {33- bears: number34- food: string35- feed: (food: string) => void36-}37-38-// Create store using the curried form of `create`39-export const useBearStore = create<BearState>()((set) => ({40- bears: 2,41- food: 'honey',42- feed: (food) => set(() => ({ food })),43-}))44-```45-46-### Using the Store in Components47-48-Inside components, you can read state and call actions. Selectors `(s) => s.bears` subscribe to only what you need.49-This reduces re-renders and improves performance. JS can do this too, but with TS your IDE autocompletes state fields.50-51-```tsx52-import { useBearStore } from './store'53-54-function BearCounter() {55- // Select only 'bears' to avoid unnecessary re-renders56- const bears = useBearStore((s) => s.bears)57- return <h1>{bears} bears around</h1>58-}59-```60-61-### Resetting the Store62-63-Resetting is useful after logout or “clear session”. We use `typeof initialState` to avoid repeating property types.64-TypeScript updates automatically if `initialState` changes. This is safer and cleaner compared to JS.65-66-```tsx67-import { create } from 'zustand'68-69-const initialState = { bears: 0, food: 'honey' }70-71-// Reuse state type dynamically72-type BearState = typeof initialState & {73- increase: (by: number) => void74- reset: () => void75-}76-77-const useBearStore = create<BearState>()((set) => ({78- ...initialState,79- increase: (by) => set((s) => ({ bears: s.bears + by })),80- reset: () => set(initialState),81-}))82-83-function ResetZoo() {84- const { bears, increase, reset } = useBearStore()85-86- return (87- <div>88- <div>{bears}</div>89- <button onClick={() => increase(5)}>Increase by 5</button>90- <button onClick={reset}>Reset</button>91- </div>92- )93-}94-```95-96-### Extracting Types97-98-Zustand provides a built-in helper called `ExtractState`. This is useful for tests, utility functions, or component props.99-It returns the full type of your store’s state and actions without having to manually redefine them. Extracting the Store type:100-101-```ts102-// store.ts103-import { create, type ExtractState } from 'zustand'104-105-export const useBearStore = create((set) => ({106- bears: 3,107- food: 'honey',108- increase: (by: number) => set((s) => ({ bears: s.bears + by })),109-}))110-111-// Extract the type of the whole store state112-export type BearState = ExtractState<typeof useBearStore>113-```114-115-Using extracted type in tests:116-117-```ts118-// test.cy.ts119-import { BearState } from './store.ts'120-121-test('should reset store', () => {122- const snapshot: BearState = useBearStore.getState()123- expect(snapshot.bears).toBeGreaterThanOrEqual(0)124-})125-```126-127-and in utility function:128-129-```ts130-// util.ts131-import { BearState } from './store.ts'132-133-function logBearState(state: BearState) {134- console.log(`We have ${state.bears} bears eating ${state.food}`)135-}136-137-logBearState(useBearStore.getState())138-```139-140-### Selectors141-142-#### Multiple Selectors143-144-Sometimes you need more than one property. Returning an object from the selector lets you access multiple fields at once.145-However, directly destructuring properties from that object can cause unnecessary re-renders.146-To avoid this, it’s recommended to wrap the selector with `useShallow`, which prevents re-renders when the selected values remain shallowly equal.147-This is more efficient than subscribing to the whole store. TypeScript ensures you can’t accidentally misspell `bears` or `food`.148-See the [API documentation](https://zustand.docs.pmnd.rs/hooks/use-shallow) for more details on `useShallow`.149-150-```tsx151-import { create } from 'zustand'152-import { useShallow } from 'zustand/react/shallow'153-154-// Bear store with explicit types155-interface BearState {156- bears: number157- food: number158-}159-160-const useBearStore = create<BearState>()(() => ({161- bears: 2,162- food: 10,163-}))164-165-// In components, you can use both stores safely166-function MultipleSelectors() {167- const { bears, food } = useBearStore(168- useShallow((state) => ({ bears: state.bears, food: state.food })),169- )170-171- return (172- <div>173- We have {food} units of food for {bears} bears174- </div>175- )176-}177-```178-179-#### Derived State with Selectors180-181-Not all values need to be stored directly - some can be computed from existing state. You can derive values using selectors.182-This avoids duplication and keeps the store minimal. TypeScript ensures `bears` is a number, so math is safe.183-184-```tsx185-import { create } from 'zustand'186-187-interface BearState {188- bears: number189- foodPerBear: number190-}191-192-const useBearStore = create<BearState>()(() => ({193- bears: 3,194- foodPerBear: 2,195-}))196-197-function TotalFood() {198- // Derived value: required amount food for all bears199- const totalFood = useBearStore((s) => s.bears * s.foodPerBear) // don't need to have extra property `{ totalFood: 6 }` in your Store200-201- return <div>We need ${totalFood} jars of honey</div>202-}203-```204-205-### Middlewares206-207-#### `combine` middleware208-209-This middleware separates initial state and actions, making the code cleaner.210-TS automatically infers types from the state and actions, no interface needed.211-This is different from JS, where type safety is missing. It’s a very popular style in TypeScript projects.212-See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/combine) for more details.213-214-```ts215-import { create } from 'zustand'216-import { combine } from 'zustand/middleware'217-218-interface BearState {219- bears: number220- increase: () => void221-}222-223-// State + actions are separated224-export const useBearStore = create<BearState>()(225- combine({ bears: 0 }, (set) => ({226- increase: () => set((s) => ({ bears: s.bears + 1 })),227- })),228-)229-```230-231-#### `devtools` middleware232-233-This middleware connects Zustand to Redux DevTools. You can inspect changes, time-travel, and debug state.234-It’s extremely useful in development. TS ensures your actions and state remain type-checked even here.235-See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/devtools) for more details.236-237-```ts238-import { create } from 'zustand'239-import { devtools } from 'zustand/middleware'240-241-interface BearState {242- bears: number243- increase: () => void244-}245-246-export const useBearStore = create<BearState>()(247- devtools((set) => ({248- bears: 0,249- increase: () => set((s) => ({ bears: s.bears + 1 })),250- })),251-)252-```253-254-#### `persist` middleware255-256-This middleware keeps your store in `localStorage` (or another storage). This means your bears survive a page refresh.257-Great for apps where persistence matters. In TS, the state type stays consistent, so no runtime surprises.258-See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/persist) for more details.259-260-```ts261-import { create } from 'zustand'262-import { persist } from 'zustand/middleware'263-264-interface BearState {265- bears: number266- increase: () => void267-}268-269-export const useBearStore = create<BearState>()(270- persist(271- (set) => ({272- bears: 0,273- increase: () => set((s) => ({ bears: s.bears + 1 })),274- }),275- { name: 'bear-storage' }, // localStorage key276- ),277-)278-```279-280-### Async Actions281-282-Actions can be async to fetch remote data. Here we fetch bears count and update state.283-TS enforces correct API response type (`BearData`). In JS you might misspell `count` - TS prevents that.284-285-```ts286-import { create } from 'zustand'287-288-interface BearData {289- count: number290-}291-292-interface BearState {293- bears: number294- fetchBears: () => Promise<void>295-}296-297-export const useBearStore = create<BearState>()((set) => ({298- bears: 0,299- fetchBears: async () => {300- const res = await fetch('/api/bears')301- const data: BearData = await res.json()302-303- set({ bears: data.count })304- },305-}))306-```307-308-### `createWithEqualityFn`309-310-Variant of `create` with equality built-in. Useful if you always want custom equality checks.311-Not common, but shows Zustand’s flexibility. TS still keeps full type inference.312-See the [API documentation](https://zustand.docs.pmnd.rs/apis/create-with-equality-fn) for more details.313-314-```ts315-import { createWithEqualityFn } from 'zustand/traditional'316-import { shallow } from 'zustand/shallow'317-318-const useBearStore = createWithEqualityFn(() => ({319- bears: 0,320-}))321-322-const bears = useBearStore((s) => s.bears, Object.is)323-// or324-const bears = useBearStore((s) => ({ bears: s.bears }), shallow)325-```326-327-### Multiple Stores328-329-You can create more than one store for different domains. For example, `BearStore` manages bears and `FishStore` manages fish.330-This keeps state isolated and easier to maintain in larger apps. With TypeScript, each store has its own strict type - you can’t accidentally mix bears and fish.331-332-```tsx333-import { create } from 'zustand'334-335-// Bear store with explicit types336-interface BearState {337- bears: number338- addBear: () => void339-}340-341-const useBearStore = create<BearState>()((set) => ({342- bears: 2,343- addBear: () => set((s) => ({ bears: s.bears + 1 })),344-}))345-346-// Fish store with explicit types347-interface FishState {348- fish: number349- addFish: () => void350-}351-352-const useFishStore = create<FishState>()((set) => ({353- fish: 5,354- addFish: () => set((s) => ({ fish: s.fish + 1 })),355-}))356-357-// In components, you can use both stores safely358-function Zoo() {359- const { bears, addBear } = useBearStore()360- const { fish, addFish } = useFishStore()361-362- return (363- <div>364- <div>365- {bears} bears and {fish} fish366- </div>367- <button onClick={addBear}>Add bear</button>368- <button onClick={addFish}>Add fish</button>369- </div>370- )371-}372-```373-374-### Conclusion375-376-Zustand together with TypeScript provides a balance: you keep the simplicity of small, minimalistic stores, while gaining the safety of strong typing.377-You don’t need boilerplate or complex patterns - state and actions live side by side, fully typed, and ready to use.378-Start with a basic store to learn the pattern, then expand gradually: use `combine` for cleaner inference, `persist` for storage, and `devtools` for debugging.deleted:docs/guides/connect-to-state-with-url-hash.md-153 removed
1----2-title: Connect to state with URL3-nav: 114----5-6-## Connect State with URL Hash7-8-If you want to connect state of a store to URL hash, you can create your own hash storage.9-10-```ts11-import { create } from 'zustand'12-import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'13-14-const hashStorage: StateStorage = {15- getItem: (key): string => {16- const searchParams = new URLSearchParams(location.hash.slice(1))17- const storedValue = searchParams.get(key) ?? ''18- return JSON.parse(storedValue)19- },20- setItem: (key, newValue): void => {21- const searchParams = new URLSearchParams(location.hash.slice(1))22- searchParams.set(key, JSON.stringify(newValue))23- location.hash = searchParams.toString()24- },25- removeItem: (key): void => {26- const searchParams = new URLSearchParams(location.hash.slice(1))27- searchParams.delete(key)28- location.hash = searchParams.toString()29- },30-}31-32-export const useBoundStore = create()(33- persist(34- (set, get) => ({35- fishes: 0,36- addAFish: () => set({ fishes: get().fishes + 1 }),37- }),38- {39- name: 'food-storage', // unique name40- storage: createJSONStorage(() => hashStorage),41- },42- ),43-)44-```45-46-## Persist and Connect State with URL Parameters (Example: URL Query Parameters)47-48-There are times when you want to conditionally connect the state to the URL.49-This example depicts usage of the URL query parameters50-while keeping it synced with another persistence implementation, like `localstorage`.51-52-If you want the URL params to always populate, the conditional check on `getUrlSearch()` can be removed.53-54-The implementation below will update the URL in place, without refresh, as the relevant states change.55-56-```ts57-import { create } from 'zustand'58-import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'59-60-const getUrlSearch = () => {61- return window.location.search.slice(1)62-}63-64-const persistentStorage: StateStorage = {65- getItem: (key): string => {66- // Check URL first67- if (getUrlSearch()) {68- const searchParams = new URLSearchParams(getUrlSearch())69- const storedValue = searchParams.get(key)70- return JSON.parse(storedValue as string)71- } else {72- // Otherwise, we should load from localstorage or alternative storage73- return JSON.parse(localStorage.getItem(key) as string)74- }75- },76- setItem: (key, newValue): void => {77- // Check if query params exist at all, can remove check if always want to set URL78- if (getUrlSearch()) {79- const searchParams = new URLSearchParams(getUrlSearch())80- searchParams.set(key, JSON.stringify(newValue))81- window.history.replaceState(null, '', `?${searchParams.toString()}`)82- }83-84- localStorage.setItem(key, JSON.stringify(newValue))85- },86- removeItem: (key): void => {87- const searchParams = new URLSearchParams(getUrlSearch())88- searchParams.delete(key)89- window.location.search = searchParams.toString()90- },91-}92-93-type LocalAndUrlStore = {94- typesOfFish: string[]95- addTypeOfFish: (fishType: string) => void96- numberOfBears: number97- setNumberOfBears: (newNumber: number) => void98-}99-100-const storageOptions = {101- name: 'fishAndBearsStore',102- storage: createJSONStorage<LocalAndUrlStore>(() => persistentStorage),103-}104-105-const useLocalAndUrlStore = create()(106- persist<LocalAndUrlStore>(107- (set) => ({108- typesOfFish: [],109- addTypeOfFish: (fishType) =>110- set((state) => ({ typesOfFish: [...state.typesOfFish, fishType] })),111-112- numberOfBears: 0,113- setNumberOfBears: (numberOfBears) => set(() => ({ numberOfBears })),114- }),115- storageOptions,116- ),117-)118-119-export default useLocalAndUrlStore120-```121-122-When generating the URL from a component, you can call buildShareableUrl:123-124-```ts125-const buildURLSuffix = (params, version = 0) => {126- const searchParams = new URLSearchParams()127-128- const zustandStoreParams = {129- state: {130- typesOfFish: params.typesOfFish,131- numberOfBears: params.numberOfBears,132- },133- version: version, // version is here because that is included with how Zustand sets the state134- }135-136- // The URL param key should match the name of the store, as specified as in storageOptions above137- searchParams.set('fishAndBearsStore', JSON.stringify(zustandStoreParams))138- return searchParams.toString()139-}140-141-export const buildShareableUrl = (params, version) => {142- return `${window.location.origin}?${buildURLSuffix(params, version)}`143-}144-```145-146-The generated URL would look like (here without any encoding, for readability):147-148-`https://localhost/search?fishAndBearsStore={"state":{"typesOfFish":["tilapia","salmon"],"numberOfBears":15},"version":0}}`149-150-### Demo151-152-- Hash: https://stackblitz.com/edit/vitejs-vite-9vg24prg153-- Query: https://stackblitz.com/edit/vitejs-vite-hyc97ynfdeleted:docs/guides/event-handler-in-pre-react-18.md-24 removed
123456789101112131415161718192021222324---title: Calling actions outside a React event handler in pre React 18nav: 9---
Because React handles `setState` synchronously if it's called outside an event handler, updating the state outside an event handler will force react to update the components synchronously. Therefore, there is a risk of encountering the zombie-child effect.In order to fix this, the action needs to be wrapped in `unstable_batchedUpdates` like so:
```jsximport { unstable_batchedUpdates } from 'react-dom' // or 'react-native'
const useFishStore = create((set) => ({ fishes: 0, increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 })),}))
const nonReactCallback = () => { unstable_batchedUpdates(() => { useFishStore.getState().increaseFishes() })}```
More details: https://github.com/pmndrs/zustand/issues/302deleted:docs/guides/flux-inspired-practice.md-77 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677---title: Flux inspired practicenav: 4---
Although Zustand is an unopinionated library, we do recommend a few patterns.These are inspired by practices originally found in [Flux](https://github.com/facebookarchive/flux),and more recently [Redux](https://redux.js.org/understanding/thinking-in-redux/three-principles),so if you are coming from another library, you should feel right at home.
However, Zustand does differ in some fundamental ways,so some terminology may not perfectly align to other libraries.
## Recommended patterns
### Single store
Your applications global state should be located in a single Zustand store.
If you have a large application, Zustand supports [splitting the store into slices](./slices-pattern.md).
### Use `set` / `setState` to update the store
Always use `set` (or `setState`) to perform updates to your store.`set` (and `setState`) ensures the described update is correctly merged and listeners are appropriately notified.
### Colocate store actions
In Zustand, state can be updated without the use of dispatched actions and reducers found in other Flux libraries.These store actions can be added directly to the store as shown below.
Optionally, by using `setState` they can be [located external to the store](./practice-with-no-store-actions.md)
```jsconst useBoundStore = create((set) => ({ storeSliceA: ..., storeSliceB: ..., storeSliceC: ..., updateX: () => set(...), updateY: () => set(...),}))```
## Redux-like patterns
If you can't live without Redux-like reducers, you can define a `dispatch` function on the root level of the store:
```typescriptconst types = { increase: 'INCREASE', decrease: 'DECREASE' }
const reducer = (state, { type, by = 1 }) => { switch (type) { case types.increase: return { grumpiness: state.grumpiness + by } case types.decrease: return { grumpiness: state.grumpiness - by } }}
const useGrumpyStore = create((set) => ({ grumpiness: 0, dispatch: (args) => set((state) => reducer(state, args)),}))
const dispatch = useGrumpyStore((state) => state.dispatch)dispatch({ type: types.increase, by: 2 })```
You could also use our redux-middleware. It wires up your main reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api.
```typescriptimport { redux } from 'zustand/middleware'
const useReduxStore = create(redux(reducer, initialState))```
Another way to update the store could be through functions wrapping the state functions. These could also handle side-effects of actions. For example, with HTTP-calls. To use Zustand in a non-reactive way, see [the readme](https://github.com/pmndrs/zustand#readingwriting-state-and-reacting-to-changes-outside-of-components).deleted:docs/guides/how-to-reset-state.md-45 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445---title: How to reset statenav: 12---
The following pattern can be used to reset the state to its initial value.
```tsconst useSomeStore = create<State & Actions>()((set, get, store) => ({ // your code here reset: () => { set(store.getInitialState()) },}))```
Resetting multiple stores at once
```tsimport type { StateCreator } from 'zustand'import { create: actualCreate } from 'zustand'
const storeResetFns = new Set<() => void>()
const resetAllStores = () => { storeResetFns.forEach((resetFn) => { resetFn() })}
export const create = (<T>() => { return (stateCreator: StateCreator<T>) => { const store = actualCreate(stateCreator) storeResetFns.add(() => { store.setState(store.getInitialState(), true) }) return store }}) as typeof actualCreate```
## Demo
- Basic: https://stackblitz.com/edit/zustand-how-to-reset-state-basic- Advanced: https://stackblitz.com/edit/zustand-how-to-reset-state-advanceddeleted:docs/guides/immutable-state-and-merging.md-59 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859---title: Immutable state and mergingnav: 3---
Like with React's `useState`, we need to update state immutably.
Here's a typical example:
```jsximport { create } from 'zustand'
const useCountStore = create((set) => ({ count: 0, inc: () => set((state) => ({ count: state.count + 1 })),}))```
The `set` function is to update state in the store.Because the state is immutable, it should have been like this:
```jsset((state) => ({ ...state, count: state.count + 1 }))```
However, as this is a common pattern, `set` actually merges state, andwe can skip the `...state` part:
```jsset((state) => ({ count: state.count + 1 }))```
## Nested objects
The `set` function merges state at only one level.If you have a nested object, you need to merge them explicitly. You will use the spread operator pattern like so:
```jsximport { create } from 'zustand'
const useCountStore = create((set) => ({ nested: { count: 0 }, inc: () => set((state) => ({ nested: { ...state.nested, count: state.nested.count + 1 }, })),}))```
For complex use cases, consider using some libraries that help with immutable updates.You can refer to [Updating nested state object values](./updating-state.md#deeply-nested-object).
## Replace flag
To disable the merging behavior, you can specify a `replace` boolean value for `set` like so:
```jsset((state) => newState, true)```deleted:docs/guides/initialize-state-with-props.md-180 removed
1----2-title: Initialize state with props3-nav: 134----5-6-In cases where [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) is needed, such as when a store should be initialized with props from a component, the recommended approach is to use a vanilla store with React.context.7-8-## Store creator with `createStore`9-10-```ts11-import { createStore } from 'zustand'12-13-interface BearProps {14- bears: number15-}16-17-interface BearState extends BearProps {18- addBear: () => void19-}20-21-type BearStore = ReturnType<typeof createBearStore>22-23-const createBearStore = (initProps?: Partial<BearProps>) => {24- const DEFAULT_PROPS: BearProps = {25- bears: 0,26- }27- return createStore<BearState>()((set) => ({28- ...DEFAULT_PROPS,29- ...initProps,30- addBear: () => set((state) => ({ bears: ++state.bears })),31- }))32-}33-```34-35-## Creating a context with `React.createContext`36-37-```ts38-import { createContext } from 'react'39-40-export const BearContext = createContext<BearStore | null>(null)41-```42-43-## Basic component usage44-45-```tsx46-// Provider implementation47-import { useState } from 'react'48-49-function App() {50- const [store] = useState(() => createBearStore())51- return (52- <BearContext.Provider value={store}>53- <BasicConsumer />54- </BearContext.Provider>55- )56-}57-```58-59-```tsx60-// Consumer component61-import { useContext } from 'react'62-import { useStore } from 'zustand'63-64-function BasicConsumer() {65- const store = useContext(BearContext)66- if (!store) throw new Error('Missing BearContext.Provider in the tree')67-68- const bears = useStore(store, (s) => s.bears)69- const addBear = useStore(store, (s) => s.addBear)70-71- return (72- <>73- <div>{bears} Bears.</div>74- <button onClick={addBear}>Add bear</button>75- </>76- )77-}78-```79-80-## Common patterns81-82-### Wrapping the context provider83-84-```tsx85-// Provider wrapper86-import { useState } from 'react'87-88-type BearProviderProps = React.PropsWithChildren<BearProps>89-90-function BearProvider({ children, ...props }: BearProviderProps) {91- const [store] = useState(() => createBearStore(props))92- return <BearContext.Provider value={store}>{children}</BearContext.Provider>93-}94-```95-96-### Extracting context logic into a custom hook97-98-```tsx99-// Mimic the hook returned by `create`100-import { useContext } from 'react'101-import { useStore } from 'zustand'102-103-function useBearContext<T>(selector: (state: BearState) => T): T {104- const store = useContext(BearContext)105- if (!store) throw new Error('Missing BearContext.Provider in the tree')106- return useStore(store, selector)107-}108-```109-110-```tsx111-// Consumer usage of the custom hook112-function CommonConsumer() {113- const bears = useBearContext((s) => s.bears)114- const addBear = useBearContext((s) => s.addBear)115- return (116- <>117- <div>{bears} Bears.</div>118- <button onClick={addBear}>Add bear</button>119- </>120- )121-}122-```123-124-### Optionally use memoized selector for stable outputs125-126-```tsx127-import { useShallow } from 'zustand/react/shallow'128-129-const meals = ['Salmon', 'Berries', 'Nuts']130-131-function CommonConsumer() {132- const bearMealsOrder = useBearContext(133- useShallow((s) =>134- Array.from({ length: s.bears }).map((_, index) =>135- meals.at(index % meals.length),136- ),137- ),138- )139- return (140- <>141- Order:142- <ul>143- {bearMealsOrder.map((meal) => (144- <li key={meal}>{meal}</li>145- ))}146- </ul>147- </>148- )149-}150-```151-152-### Optionally allow using a custom equality function153-154-```tsx155-// Allow custom equality function by using useStoreWithEqualityFn instead of useStore156-import { useContext } from 'react'157-import { useStoreWithEqualityFn } from 'zustand/traditional'158-159-function useBearContext<T>(160- selector: (state: BearState) => T,161- equalityFn?: (left: T, right: T) => boolean,162-): T {163- const store = useContext(BearContext)164- if (!store) throw new Error('Missing BearContext.Provider in the tree')165- return useStoreWithEqualityFn(store, selector, equalityFn)166-}167-```168-169-### Complete example170-171-```tsx172-// Provider wrapper & custom hook consumer173-function App2() {174- return (175- <BearProvider bears={2}>176- <HookConsumer />177- </BearProvider>178- )179-}180-```deleted:docs/guides/maps-and-sets-usage.md-115 removed
1----2-title: Map and Set Usage3-nav: 104----5-6-# Map and Set in Zustand7-8-Map and Set are mutable data structures. To use them in Zustand, you must create new instances when updating.9-10-## Map11-12-### Reading a Map13-14-```typescript15-const foo = useSomeStore((state) => state.foo)16-```17-18-### Updating a Map19-20-Always create a new Map instance:21-22-```ts23-// Update single entry24-set((state) => ({25- foo: new Map(state.foo).set(key, value),26-}))27-28-// Delete entry29-set((state) => {30- const next = new Map(state.foo)31- next.delete(key)32- return { foo: next }33-})34-35-// Update multiple entries36-set((state) => {37- const next = new Map(state.foo)38- next.set('key1', 'value1')39- next.set('key2', 'value2')40- return { foo: next }41-})42-43-// Clear44-set({ foo: new Map() })45-```46-47-## Set48-49-### Reading a Set50-51-```ts52-const bar = useSomeStore((state) => state.bar)53-```54-55-### Updating a Set56-57-Always create a new Set instance:58-59-```ts60-// Add item61-set((state) => ({62- bar: new Set(state.bar).add(item),63-}))64-65-// Delete item66-set((state) => {67- const next = new Set(state.bar)68- next.delete(item)69- return { bar: next }70-})71-72-// Toggle item73-set((state) => {74- const next = new Set(state.bar)75- next.has(item) ? next.delete(item) : next.add(item)76- return { bar: next }77-})78-79-// Clear80-set({ bar: new Set() })81-```82-83-## Why New Instances?84-85-Zustand detects changes by comparing references. Mutating a Map or Set doesn't change its reference:86-87-```ts88-// ❌ Wrong - same reference, no re-render89-set((state) => {90- state.foo.set(key, value)91- return { foo: state.foo }92-})93-94-// ✅ Correct - new reference, triggers re-render95-set((state) => ({96- foo: new Map(state.foo).set(key, value),97-}))98-```99-100-## Pitfall: Type Hints for Empty Collections101-102-Provide type hints when initializing empty Maps and Sets:103-104-```ts105-{106- ids: new Set([] as string[]),107- users: new Map([] as [string, User][])108-}109-```110-111-Without type hints, TypeScript infers `never[]` which prevents adding items later.112-113-## Demos114-115-Basic: https://stackblitz.com/edit/vitejs-vite-5cu5ddvxdeleted:docs/guides/nextjs.md-316 removed
1----2-title: Setup with Next.js3-nav: 174----5-6-> [!NOTE]7-> We will be updating this guide soon based on our discussion in https://github.com/pmndrs/zustand/discussions/2740.8-9-[Next.js](https://nextjs.org) is a popular server-side rendering framework for React that presents10-some unique challenges for using Zustand properly.11-Keep in mind that Zustand store is a global12-variable (AKA module state) making it optional to use a `Context`.13-These challenges include:14-15-- **Per-request store:** A Next.js server can handle multiple requests simultaneously. This means16- that the store should be created per request and should not be shared across requests.17-- **SSR friendly:** Next.js applications are rendered twice, first on the server18- and again on the client. Having different outputs on both the client and the server will result19- in "hydration errors." The store will have to be initialized on the server and then20- re-initialized on the client with the same data in order to avoid that. Please read more about21- that in our [SSR and Hydration](./ssr-and-hydration.md) guide.22-- **SPA routing friendly:** Next.js supports a hybrid model for client side routing, which means23- that in order to reset a store, we need to initialize it at the component level using a24- `Context`.25-- **Server caching friendly:** Recent versions of Next.js (specifically applications using the App26- Router architecture) support aggressive server caching. Due to our store being a **module state**,27- it is completely compatible with this caching.28-29-We have these general recommendations for the appropriate use of Zustand:30-31-- **No global stores** - Because the store should not be shared across requests, it should not be defined32- as a global variable. Instead, the store should be created per request.33-- **React Server Components should not read from or write to the store** - RSCs cannot use hooks or context. They aren't34- meant to be stateful. Having an RSC read from or write values to a global store violates the35- architecture of Next.js.36-37-### Creating a store per request38-39-Let's write our store factory function that will create a new store for each40-request.41-42-```json43-// tsconfig.json44-{45- "compilerOptions": {46- "lib": ["dom", "dom.iterable", "esnext"],47- "allowJs": true,48- "skipLibCheck": true,49- "strict": true,50- "noEmit": true,51- "esModuleInterop": true,52- "module": "esnext",53- "moduleResolution": "bundler",54- "resolveJsonModule": true,55- "isolatedModules": true,56- "jsx": "preserve",57- "incremental": true,58- "plugins": [59- {60- "name": "next"61- }62- ],63- "paths": {64- "@/*": ["./src/*"]65- }66- },67- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],68- "exclude": ["node_modules"]69-}70-```71-72-> **Note:** do not forget to remove all comments from your `tsconfig.json` file.73-74-### Initializing the store75-76-```ts77-// src/stores/counter-store.ts78-import { createStore } from 'zustand/vanilla'79-80-export type CounterState = {81- count: number82-}83-84-export type CounterActions = {85- decrementCount: () => void86- incrementCount: () => void87-}88-89-export type CounterStore = CounterState & CounterActions90-91-export const defaultInitState: CounterState = {92- count: 0,93-}94-95-export const createCounterStore = (96- initState: CounterState = defaultInitState,97-) => {98- return createStore<CounterStore>()((set) => ({99- ...initState,100- decrementCount: () => set((state) => ({ count: state.count - 1 })),101- incrementCount: () => set((state) => ({ count: state.count + 1 })),102- }))103-}104-```105-106-### Providing the store107-108-Let's use the `createCounterStore` in our component and share it using a context provider.109-110-```tsx111-// src/providers/counter-store-provider.tsx112-'use client'113-114-import { type ReactNode, createContext, useState, useContext } from 'react'115-import { useStore } from 'zustand'116-117-import { type CounterStore, createCounterStore } from '@/stores/counter-store'118-119-export type CounterStoreApi = ReturnType<typeof createCounterStore>120-121-export const CounterStoreContext = createContext<CounterStoreApi | undefined>(122- undefined,123-)124-125-export interface CounterStoreProviderProps {126- children: ReactNode127-}128-129-export const CounterStoreProvider = ({130- children,131-}: CounterStoreProviderProps) => {132- const [store] = useState(() => createCounterStore())133- return (134- <CounterStoreContext.Provider value={store}>135- {children}136- </CounterStoreContext.Provider>137- )138-}139-140-export const useCounterStore = <T,>(141- selector: (store: CounterStore) => T,142-): T => {143- const counterStoreContext = useContext(CounterStoreContext)144- if (!counterStoreContext) {145- throw new Error(`useCounterStore must be used within CounterStoreProvider`)146- }147-148- return useStore(counterStoreContext, selector)149-}150-```151-152-> **Note:** In this example, we ensure that this component is re-render-safe by checking the153-> value of the reference, so that the store is only created once. This component will only be154-> rendered once per request on the server, but might be re-rendered multiple times on the client if155-> there are stateful client components located above this component in the tree, or if this component156-> also contains other mutable state that causes a re-render.157-158-### Using the store with different architectures159-160-There are two architectures for a Next.js application: the161-[Pages Router](https://nextjs.org/docs/pages/building-your-application/routing) and the162-[App Router](https://nextjs.org/docs/app/building-your-application/routing). The usage of Zustand on163-both architectures should be the same with slight differences related to each architecture.164-165-#### Pages Router166-167-```tsx168-// src/components/pages/home-page.tsx169-import { useCounterStore } from '@/providers/counter-store-provider'170-171-export const HomePage = () => {172- const { count, incrementCount, decrementCount } = useCounterStore(173- (state) => state,174- )175-176- return (177- <div>178- Count: {count}179- <hr />180- <button type="button" onClick={incrementCount}>181- Increment Count182- </button>183- <button type="button" onClick={decrementCount}>184- Decrement Count185- </button>186- </div>187- )188-}189-```190-191-```tsx192-// src/_app.tsx193-import type { AppProps } from 'next/app'194-195-import { CounterStoreProvider } from '@/providers/counter-store-provider'196-197-export default function App({ Component, pageProps }: AppProps) {198- return (199- <CounterStoreProvider>200- <Component {...pageProps} />201- </CounterStoreProvider>202- )203-}204-```205-206-```tsx207-// src/pages/index.tsx208-import { HomePage } from '@/components/pages/home-page'209-210-export default function Home() {211- return <HomePage />212-}213-```214-215-> **Note:** creating a store per route would require creating and sharing the store216-> at page (route) component level. Try not to use this if you do not need to create217-> a store per route.218-219-```tsx220-// src/pages/index.tsx221-import { CounterStoreProvider } from '@/providers/counter-store-provider'222-import { HomePage } from '@/components/pages/home-page'223-224-export default function Home() {225- return (226- <CounterStoreProvider>227- <HomePage />228- </CounterStoreProvider>229- )230-}231-```232-233-#### App Router234-235-```tsx236-// src/components/pages/home-page.tsx237-'use client'238-239-import { useCounterStore } from '@/providers/counter-store-provider'240-241-export const HomePage = () => {242- const { count, incrementCount, decrementCount } = useCounterStore(243- (state) => state,244- )245-246- return (247- <div>248- Count: {count}249- <hr />250- <button type="button" onClick={incrementCount}>251- Increment Count252- </button>253- <button type="button" onClick={decrementCount}>254- Decrement Count255- </button>256- </div>257- )258-}259-```260-261-```tsx262-// src/app/layout.tsx263-import type { Metadata } from 'next'264-import { Inter } from 'next/font/google'265-import './globals.css'266-267-import { CounterStoreProvider } from '@/providers/counter-store-provider'268-269-const inter = Inter({ subsets: ['latin'] })270-271-export const metadata: Metadata = {272- title: 'Create Next App',273- description: 'Generated by create next app',274-}275-276-export default function RootLayout({277- children,278-}: Readonly<{279- children: React.ReactNode280-}>) {281- return (282- <html lang="en">283- <body className={inter.className}>284- <CounterStoreProvider>{children}</CounterStoreProvider>285- </body>286- </html>287- )288-}289-```290-291-```tsx292-// src/app/page.tsx293-import { HomePage } from '@/components/pages/home-page'294-295-export default function Home() {296- return <HomePage />297-}298-```299-300-> **Note:** creating a store per route would require creating and sharing the store301-> at page (route) component level. Try not to use this if you do not need to create302-> a store per route.303-304-```tsx305-// src/app/page.tsx306-import { CounterStoreProvider } from '@/providers/counter-store-provider'307-import { HomePage } from '@/components/pages/home-page'308-309-export default function Home() {310- return (311- <CounterStoreProvider>312- <HomePage />313- </CounterStoreProvider>314- )315-}316-```deleted:docs/guides/practice-with-no-store-actions.md-42 removed
1----2-title: Practice with no store actions3-nav: 64----5-6-The recommended usage is to colocate actions and states within the store (let your actions be located together with your state).7-8-For example:9-10-```js11-export const useBoundStore = create((set) => ({12- count: 0,13- text: 'hello',14- inc: () => set((state) => ({ count: state.count + 1 })),15- setText: (text) => set({ text }),16-}))17-```18-19-This creates a self-contained store with data and actions together.20-21----22-23-An alternative approach is to define actions at module level, external to the store.24-25-```js26-export const useBoundStore = create(() => ({27- count: 0,28- text: 'hello',29-}))30-31-export const inc = () =>32- useBoundStore.setState((state) => ({ count: state.count + 1 }))33-34-export const setText = (text) => useBoundStore.setState({ text })35-```36-37-This has a few advantages:38-39-- It doesn't require a hook to call an action;40-- It facilitates code splitting.41-42-While this pattern doesn't offer any downsides, some may prefer colocating due to its encapsulated nature.deleted:docs/guides/prevent-rerenders-with-use-shallow.md-63 removed
1----2-title: Prevent rerenders with useShallow3-nav: 154----5-6-When you need to subscribe to a computed state from a store, the recommended way is to7-use a selector.8-9-The computed selector will cause a rerender if the output has changed according to [Object.is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is?retiredLocale=it).10-11-In this case you might want to use `useShallow` to avoid a rerender if the computed value is always shallow12-equal the previous one.13-14-## Example15-16-We have a store that associates to each bear a meal and we want to render their names.17-18-```js19-import { create } from 'zustand'20-21-const useMeals = create(() => ({22- papaBear: 'large porridge-pot',23- mamaBear: 'middle-size porridge pot',24- littleBear: 'A little, small, wee pot',25-}))26-27-export const BearNames = () => {28- const names = useMeals((state) => Object.keys(state))29-30- return <div>{names.join(', ')}</div>31-}32-```33-34-Now papa bear wants a pizza instead:35-36-```js37-useMeals.setState({38- papaBear: 'a large pizza',39-})40-```41-42-This change causes `BearNames` rerenders even though the actual output of `names` has not changed according to shallow equal.43-44-We can fix that using `useShallow`!45-46-```js47-import { create } from 'zustand'48-import { useShallow } from 'zustand/react/shallow'49-50-const useMeals = create(() => ({51- papaBear: 'large porridge-pot',52- mamaBear: 'middle-size porridge pot',53- littleBear: 'A little, small, wee pot',54-}))55-56-export const BearNames = () => {57- const names = useMeals(useShallow((state) => Object.keys(state)))58-59- return <div>{names.join(', ')}</div>60-}61-```62-63-Now they can all order other meals without causing unnecessary rerenders of our `BearNames` component.deleted:docs/guides/slices-pattern.md-120 removed
1----2-title: Slices Pattern3-nav: 144----5-6-## Slicing the store into smaller stores7-8-Your store can become bigger and bigger and tougher to maintain as you add more features.9-10-You can divide your main store into smaller individual stores to achieve modularity. This is simple to accomplish in Zustand!11-12-The first individual store:13-14-```js15-export const createFishSlice = (set) => ({16- fishes: 0,17- addFish: () => set((state) => ({ fishes: state.fishes + 1 })),18-})19-```20-21-Another individual store:22-23-```js24-export const createBearSlice = (set) => ({25- bears: 0,26- addBear: () => set((state) => ({ bears: state.bears + 1 })),27- eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),28-})29-```30-31-You can now combine both the stores into **one bounded store**:32-33-```js34-import { create } from 'zustand'35-import { createBearSlice } from './bearSlice'36-import { createFishSlice } from './fishSlice'37-38-export const useBoundStore = create((...a) => ({39- ...createBearSlice(...a),40- ...createFishSlice(...a),41-}))42-```43-44-### Usage in a React component45-46-```jsx47-import { useBoundStore } from './stores/useBoundStore'48-49-function App() {50- const bears = useBoundStore((state) => state.bears)51- const fishes = useBoundStore((state) => state.fishes)52- const addBear = useBoundStore((state) => state.addBear)53- return (54- <div>55- <h2>Number of bears: {bears}</h2>56- <h2>Number of fishes: {fishes}</h2>57- <button onClick={() => addBear()}>Add a bear</button>58- </div>59- )60-}61-62-export default App63-```64-65-### Updating multiple stores66-67-You can update multiple stores, at the same time, in a single function.68-69-```js70-export const createBearFishSlice = (set, get) => ({71- addBearAndFish: () => {72- get().addBear()73- get().addFish()74- },75-})76-```77-78-Combining all the stores together is the same as before.79-80-```js81-import { create } from 'zustand'82-import { createBearSlice } from './bearSlice'83-import { createFishSlice } from './fishSlice'84-import { createBearFishSlice } from './createBearFishSlice'85-86-export const useBoundStore = create((...a) => ({87- ...createBearSlice(...a),88- ...createFishSlice(...a),89- ...createBearFishSlice(...a),90-}))91-```92-93-## Adding middlewares94-95-Adding middlewares to a combined store is the same as with other normal stores.96-97-Adding [`persist` middleware](../integrations/persisting-store-data.md) to our `useBoundStore`:98-99-```js100-import { create } from 'zustand'101-import { createBearSlice } from './bearSlice'102-import { createFishSlice } from './fishSlice'103-import { persist } from 'zustand/middleware'104-105-export const useBoundStore = create(106- persist(107- (...a) => ({108- ...createBearSlice(...a),109- ...createFishSlice(...a),110- }),111- { name: 'bound-store' },112- ),113-)114-```115-116-Please keep in mind you should only apply middlewares in the combined store. Applying them inside individual slices can lead to unexpected issues.117-118-## Usage with TypeScript119-120-A detailed guide on how to use the slice pattern in Zustand with TypeScript can be found [here](./advanced-typescript.md#slices-pattern).deleted:docs/guides/ssr-and-hydration.md-198 removed
1----2-title: SSR and Hydration3-nav: 164----5-6-## Server-side Rendering (SSR)7-8-Server-side Rendering (SSR) is a technique that helps us render our components into9-HTML strings on the server, send them directly to the browser, and finally "hydrate" the10-static markup into a fully interactive app on the client.11-12-### React13-14-Let's say we want to render a stateless app using React. In order to do that, we need15-to use `express`, `react` and `react-dom/server`. We don't need `react-dom/client`16-since it's a stateless app.17-18-Let's dive into that:19-20-- `express` helps us build a web app that we can run using Node,21-- `react` helps us build the UI components that we use in our app,22-- `react-dom/server` helps us render our components on a server.23-24-```json25-// tsconfig.json26-{27- "compilerOptions": {28- "noImplicitAny": false,29- "noEmitOnError": true,30- "removeComments": false,31- "sourceMap": true,32- "target": "esnext"33- },34- "include": ["**/*"]35-}36-```37-38-> **Note:** do not forget to remove all comments from your `tsconfig.json` file.39-40-```tsx41-// app.tsx42-export const App = () => {43- return (44- <html>45- <head>46- <meta charSet="utf-8" />47- <meta name="viewport" content="width=device-width, initial-scale=1" />48- <title>Static Server-side-rendered App</title>49- </head>50- <body>51- <div>Hello World!</div>52- </body>53- </html>54- )55-}56-```57-58-```tsx59-// server.tsx60-import express from 'express'61-import React from 'react'62-import ReactDOMServer from 'react-dom/server'63-64-import { App } from './app.tsx'65-66-const port = Number.parseInt(process.env.PORT || '3000', 10)67-const app = express()68-69-app.get('/', (_, res) => {70- const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {71- onShellReady() {72- res.setHeader('content-type', 'text/html')73- pipe(res)74- },75- })76-})77-78-app.listen(port, () => {79- console.log(`Server is listening at ${port}`)80-})81-```82-83-```sh84-tsc --build85-```86-87-```sh88-node server.js89-```90-91-## Hydration92-93-Hydration turns the initial HTML snapshot from the server into a fully interactive app94-that runs in the browser. The right way to "hydrate" a component is by using `hydrateRoot`.95-96-### React97-98-Let's say we want to render a stateful app using React. In order to do that we need to99-use `express`, `react`, `react-dom/server` and `react-dom/client`.100-101-Let's dive into that:102-103-- `express` helps us build a web app that we can run using Node,104-- `react` helps us build the UI components that we use in our app,105-- `react-dom/server` helps us render our components on a server,106-- `react-dom/client` helps us hydrate our components on a client.107-108-> **Note:** Do not forget that even if we can render our components on a server, it is109-> important to "hydrate" them on a client to make them interactive.110-111-```json112-// tsconfig.json113-{114- "compilerOptions": {115- "noImplicitAny": false,116- "noEmitOnError": true,117- "removeComments": false,118- "sourceMap": true,119- "target": "esnext"120- },121- "include": ["**/*"]122-}123-```124-125-> **Note:** do not forget to remove all comments in your `tsconfig.json` file.126-127-```tsx128-// app.tsx129-export const App = () => {130- return (131- <html>132- <head>133- <meta charSet="utf-8" />134- <meta name="viewport" content="width=device-width, initial-scale=1" />135- <title>Static Server-side-rendered App</title>136- </head>137- <body>138- <div>Hello World!</div>139- </body>140- </html>141- )142-}143-```144-145-```tsx146-// main.tsx147-import ReactDOMClient from 'react-dom/client'148-149-import { App } from './app.tsx'150-151-ReactDOMClient.hydrateRoot(document, <App />)152-```153-154-```tsx155-// server.tsx156-import express from 'express'157-import React from 'react'158-import ReactDOMServer from 'react-dom/server'159-160-import { App } from './app.tsx'161-162-const port = Number.parseInt(process.env.PORT || '3000', 10)163-const app = express()164-165-app.use('/', (_, res) => {166- const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {167- bootstrapScripts: ['/main.js'],168- onShellReady() {169- res.setHeader('content-type', 'text/html')170- pipe(res)171- },172- })173-})174-175-app.listen(port, () => {176- console.log(`Server is listening at ${port}`)177-})178-```179-180-```sh181-tsc --build182-```183-184-```sh185-node server.js186-```187-188-> **Warning:** The React tree you pass to `hydrateRoot` needs to produce the same output as it did on the server.189-> The most common causes leading to hydration errors include:190->191-> - Extra whitespace (like newlines) around the React-generated HTML inside the root node.192-> - Using checks like typeof window !== 'undefined' in your rendering logic.193-> - Using browser-only APIs like `window.matchMedia` in your rendering logic.194-> - Rendering different data on the server and the client.195->196-> React recovers from some hydration errors, but you must fix them like other bugs. In the best case, they’ll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.197-198-You can read more about the caveats and pitfalls here: [hydrateRoot](https://react.dev/reference/react-dom/client/hydrateRoot)deleted:docs/guides/testing.md-741 removed
1----2-title: Testing3-description: Writing Tests4-nav: 85----6-7-## Setting Up a Test Environment8-9-### Test Runners10-11-Usually, your test runner needs to be configured to run JavaScript/TypeScript syntax. If you're12-going to be testing UI components, you will likely need to configure the test runner to use JSDOM13-to provide a mock DOM environment.14-15-See these resources for test runner configuration instructions:16-17-- **Jest**18- - [Jest: Getting Started](https://jestjs.io/docs/getting-started)19- - [Jest: Configuration - Test Environment](https://jestjs.io/docs/configuration#testenvironment-string)20-- **Vitest**21- - [Vitest: Getting Started](https://vitest.dev/guide)22- - [Vitest: Configuration - Test Environment](https://vitest.dev/config/#environment)23-24-### UI and Network Testing Tools25-26-**We recommend using [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)27-to test out React components that connect to Zustand**. RTL is a simple and complete React DOM28-testing utility that encourages good testing practices. It uses ReactDOM's `render` function and29-`act` from `react-dom/tests-utils`. Furthermore, [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)30-is the alternative to RTL to test out React Native components. The [Testing Library](https://testing-library.com/)31-family of tools also includes adapters for many other popular frameworks.32-33-We also recommend using [Mock Service Worker (MSW)](https://mswjs.io/) to mock network requests, as34-this means your application logic does not need to be changed or mocked when writing tests.35-36-- **React Testing Library (DOM)**37- - [DOM Testing Library: Setup](https://testing-library.com/docs/dom-testing-library/setup)38- - [React Testing Library: Setup](https://testing-library.com/docs/react-testing-library/setup)39- - [Testing Library Jest-DOM Matchers](https://testing-library.com/docs/ecosystem-jest-dom)40-- **Native Testing Library (React Native)**41- - [Native Testing Library: Setup](https://testing-library.com/docs/react-native-testing-library/setup)42-- **User Event Testing Library (DOM)**43- - [User Event Testing Library: Setup](https://testing-library.com/docs/user-event/setup)44-- **TypeScript for Jest**45- - [TypeScript for Jest: Setup](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation)46-- **TypeScript for Node**47- - [TypeScript for Node: Setup](https://typestrong.org/ts-node/docs/installation)48-- **Mock Service Worker**49- - [MSW: Installation](https://mswjs.io/docs/getting-started/install)50- - [MSW: Setting up mock requests](https://mswjs.io/docs/getting-started/mocks/rest-api)51- - [MSW: Mock server configuration for Node](https://mswjs.io/docs/getting-started/integrate/node)52-53-## Setting Up Zustand for testing54-55-> **Note**: Since Jest and Vitest have slight differences, like Vitest using **ES modules** and Jest using56-> **CommonJS modules**, you need to keep that in mind if you are using Vitest instead of Jest.57-58-The mock provided below will enable the relevant test runner to reset the zustand stores after each test.59-60-### Shared code just for testing purposes61-62-This shared code was added to avoid code duplication in our demo since we use the same counter store63-creator for both implementations, with and without `Context` API — `createStore` and `create`, respectively.64-65-```ts66-// shared/counter-store-creator.ts67-import { type StateCreator } from 'zustand'68-69-export type CounterStore = {70- count: number71- inc: () => void72-}73-74-export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({75- count: 1,76- inc: () => set((state) => ({ count: state.count + 1 })),77-})78-```79-80-### Jest81-82-In the next steps we are going to setup our Jest environment in order to mock Zustand.83-84-```ts85-// __mocks__/zustand.ts86-import { act } from '@testing-library/react'87-import type * as ZustandExportedTypes from 'zustand'88-export * from 'zustand'89-90-const { create: actualCreate, createStore: actualCreateStore } =91- jest.requireActual<typeof ZustandExportedTypes>('zustand')92-93-// a variable to hold reset functions for all stores declared in the app94-export const storeResetFns = new Set<() => void>()95-96-const createUncurried = <T>(97- stateCreator: ZustandExportedTypes.StateCreator<T>,98-) => {99- const store = actualCreate(stateCreator)100- const initialState = store.getInitialState()101- storeResetFns.add(() => {102- store.setState(initialState, true)103- })104- return store105-}106-107-// when creating a store, we get its initial state, create a reset function and add it in the set108-export const create = (<T>(109- stateCreator: ZustandExportedTypes.StateCreator<T>,110-) => {111- console.log('zustand create mock')112-113- // to support curried version of create114- return typeof stateCreator === 'function'115- ? createUncurried(stateCreator)116- : createUncurried117-}) as typeof ZustandExportedTypes.create118-119-const createStoreUncurried = <T>(120- stateCreator: ZustandExportedTypes.StateCreator<T>,121-) => {122- const store = actualCreateStore(stateCreator)123- const initialState = store.getInitialState()124- storeResetFns.add(() => {125- store.setState(initialState, true)126- })127- return store128-}129-130-// when creating a store, we get its initial state, create a reset function and add it in the set131-export const createStore = (<T>(132- stateCreator: ZustandExportedTypes.StateCreator<T>,133-) => {134- console.log('zustand createStore mock')135-136- // to support curried version of createStore137- return typeof stateCreator === 'function'138- ? createStoreUncurried(stateCreator)139- : createStoreUncurried140-}) as typeof ZustandExportedTypes.createStore141-142-// reset all stores after each test run143-afterEach(() => {144- act(() => {145- storeResetFns.forEach((resetFn) => {146- resetFn()147- })148- })149-})150-```151-152-```ts153-// setup-jest.ts154-import '@testing-library/jest-dom'155-```156-157-```ts158-// jest.config.ts159-import type { JestConfigWithTsJest } from 'ts-jest'160-161-const config: JestConfigWithTsJest = {162- preset: 'ts-jest',163- testEnvironment: 'jsdom',164- setupFilesAfterEnv: ['./setup-jest.ts'],165-}166-167-export default config168-```169-170-> **Note**: to use TypeScript we need to install two packages `ts-jest` and `ts-node`.171-172-### Vitest173-174-In the next steps we are going to setup our Vitest environment in order to mock Zustand.175-176-> **Warning:** In Vitest you can change the [root](https://vitest.dev/config/#root).177-> Due to that, you need make sure that you are creating your `__mocks__` directory in the right place.178-> Let's say that you change the **root** to `./src`, that means you need to create a `__mocks__`179-> directory under `./src`. The end result would be `./src/__mocks__`, rather than `./__mocks__`.180-> Creating `__mocks__` directory in the wrong place can lead to issues when using Vitest.181-182-```ts183-// __mocks__/zustand.ts184-import { act } from '@testing-library/react'185-import type * as ZustandExportedTypes from 'zustand'186-export * from 'zustand'187-188-const { create: actualCreate, createStore: actualCreateStore } =189- await vi.importActual<typeof ZustandExportedTypes>('zustand')190-191-// a variable to hold reset functions for all stores declared in the app192-export const storeResetFns = new Set<() => void>()193-194-const createUncurried = <T>(195- stateCreator: ZustandExportedTypes.StateCreator<T>,196-) => {197- const store = actualCreate(stateCreator)198- const initialState = store.getInitialState()199- storeResetFns.add(() => {200- store.setState(initialState, true)201- })202- return store203-}204-205-// when creating a store, we get its initial state, create a reset function and add it in the set206-export const create = (<T>(207- stateCreator: ZustandExportedTypes.StateCreator<T>,208-) => {209- console.log('zustand create mock')210-211- // to support curried version of create212- return typeof stateCreator === 'function'213- ? createUncurried(stateCreator)214- : createUncurried215-}) as typeof ZustandExportedTypes.create216-217-const createStoreUncurried = <T>(218- stateCreator: ZustandExportedTypes.StateCreator<T>,219-) => {220- const store = actualCreateStore(stateCreator)221- const initialState = store.getInitialState()222- storeResetFns.add(() => {223- store.setState(initialState, true)224- })225- return store226-}227-228-// when creating a store, we get its initial state, create a reset function and add it in the set229-export const createStore = (<T>(230- stateCreator: ZustandExportedTypes.StateCreator<T>,231-) => {232- console.log('zustand createStore mock')233-234- // to support curried version of createStore235- return typeof stateCreator === 'function'236- ? createStoreUncurried(stateCreator)237- : createStoreUncurried238-}) as typeof ZustandExportedTypes.createStore239-240-// reset all stores after each test run241-afterEach(() => {242- act(() => {243- storeResetFns.forEach((resetFn) => {244- resetFn()245- })246- })247-})248-```249-250-> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need251-> to add `import { afterEach, vi } from 'vitest'` at the top.252-253-```ts254-// global.d.ts255-/// <reference types="vite/client" />256-/// <reference types="vitest/globals" />257-```258-259-> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we do260-> need to remove `/// <reference types="vitest/globals" />`.261-262-```ts263-// setup-vitest.ts264-import '@testing-library/jest-dom/vitest'265-266-vi.mock('zustand') // to make it work like Jest (auto-mocking)267-```268-269-> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need270-> to add `import { vi } from 'vitest'` at the top.271-272-```ts273-// vitest.config.ts274-import { defineConfig, mergeConfig } from 'vitest/config'275-import viteConfig from './vite.config'276-277-export default defineConfig((configEnv) =>278- mergeConfig(279- viteConfig(configEnv),280- defineConfig({281- test: {282- globals: true,283- environment: 'jsdom',284- setupFiles: ['./setup-vitest.ts'],285- },286- }),287- ),288-)289-```290-291-### Testing Components292-293-In the next examples we are going to use `useCounterStore`294-295-> **Note**: all of these examples are written using TypeScript.296-297-```ts298-// shared/counter-store-creator.ts299-import { type StateCreator } from 'zustand'300-301-export type CounterStore = {302- count: number303- inc: () => void304-}305-306-export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({307- count: 1,308- inc: () => set((state) => ({ count: state.count + 1 })),309-})310-```311-312-```ts313-// stores/use-counter-store.ts314-import { create } from 'zustand'315-316-import {317- type CounterStore,318- counterStoreCreator,319-} from '../shared/counter-store-creator'320-321-export const useCounterStore = create<CounterStore>()(counterStoreCreator)322-```323-324-```tsx325-// contexts/use-counter-store-context.tsx326-import { type ReactNode, createContext, useContext, useState } from 'react'327-import { createStore } from 'zustand'328-import { useStoreWithEqualityFn } from 'zustand/traditional'329-import { shallow } from 'zustand/shallow'330-331-import {332- type CounterStore,333- counterStoreCreator,334-} from '../shared/counter-store-creator'335-336-export const createCounterStore = () => {337- return createStore<CounterStore>(counterStoreCreator)338-}339-340-export type CounterStoreApi = ReturnType<typeof createCounterStore>341-342-export const CounterStoreContext = createContext<CounterStoreApi | undefined>(343- undefined,344-)345-346-export interface CounterStoreProviderProps {347- children: ReactNode348-}349-350-export const CounterStoreProvider = ({351- children,352-}: CounterStoreProviderProps) => {353- const [store] = useState(() => createCounterStore())354- return (355- <CounterStoreContext.Provider value={store}>356- {children}357- </CounterStoreContext.Provider>358- )359-}360-361-export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T362-363-export const useCounterStoreContext = <T,>(364- selector: UseCounterStoreContextSelector<T>,365-): T => {366- const counterStoreContext = useContext(CounterStoreContext)367-368- if (counterStoreContext === undefined) {369- throw new Error(370- 'useCounterStoreContext must be used within CounterStoreProvider',371- )372- }373-374- return useStoreWithEqualityFn(counterStoreContext, selector, shallow)375-}376-```377-378-```tsx379-// components/counter/counter.tsx380-import { useCounterStore } from '../../stores/use-counter-store'381-382-export function Counter() {383- const { count, inc } = useCounterStore()384-385- return (386- <div>387- <h2>Counter Store</h2>388- <h4>{count}</h4>389- <button onClick={inc}>One Up</button>390- </div>391- )392-}393-```394-395-```ts396-// components/counter/index.ts397-export * from './counter'398-```399-400-```tsx401-// components/counter/counter.test.tsx402-import { act, render, screen } from '@testing-library/react'403-import userEvent from '@testing-library/user-event'404-405-import { Counter } from './counter'406-407-describe('Counter', () => {408- test('should render with initial state of 1', async () => {409- renderCounter()410-411- expect(await screen.findByText(/^1$/)).toBeInTheDocument()412- expect(413- await screen.findByRole('button', { name: /one up/i }),414- ).toBeInTheDocument()415- })416-417- test('should increase count by clicking a button', async () => {418- const user = userEvent.setup()419-420- renderCounter()421-422- expect(await screen.findByText(/^1$/)).toBeInTheDocument()423-424- await user.click(await screen.findByRole('button', { name: /one up/i }))425-426- expect(await screen.findByText(/^2$/)).toBeInTheDocument()427- })428-})429-430-const renderCounter = () => {431- return render(<Counter />)432-}433-```434-435-```tsx436-// components/counter-with-context/counter-with-context.tsx437-import {438- CounterStoreProvider,439- useCounterStoreContext,440-} from '../../contexts/use-counter-store-context'441-442-const Counter = () => {443- const { count, inc } = useCounterStoreContext((state) => state)444-445- return (446- <div>447- <h2>Counter Store Context</h2>448- <h4>{count}</h4>449- <button onClick={inc}>One Up</button>450- </div>451- )452-}453-454-export const CounterWithContext = () => {455- return (456- <CounterStoreProvider>457- <Counter />458- </CounterStoreProvider>459- )460-}461-```462-463-```tsx464-// components/counter-with-context/index.ts465-export * from './counter-with-context'466-```467-468-```tsx469-// components/counter-with-context/counter-with-context.test.tsx470-import { act, render, screen } from '@testing-library/react'471-import userEvent from '@testing-library/user-event'472-473-import { CounterWithContext } from './counter-with-context'474-475-describe('CounterWithContext', () => {476- test('should render with initial state of 1', async () => {477- renderCounterWithContext()478-479- expect(await screen.findByText(/^1$/)).toBeInTheDocument()480- expect(481- await screen.findByRole('button', { name: /one up/i }),482- ).toBeInTheDocument()483- })484-485- test('should increase count by clicking a button', async () => {486- const user = userEvent.setup()487-488- renderCounterWithContext()489-490- expect(await screen.findByText(/^1$/)).toBeInTheDocument()491-492- await user.click(await screen.findByRole('button', { name: /one up/i }))493-494- expect(await screen.findByText(/^2$/)).toBeInTheDocument()495- })496-})497-498-const renderCounterWithContext = () => {499- return render(<CounterWithContext />)500-}501-```502-503-> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need504-> to add `import { describe, test, expect } from 'vitest'` at the top of each test file.505-506-### Testing Stores507-508-In the next examples we are going to use `useCounterStore`509-510-> **Note**: all of these examples are written using TypeScript.511-512-```ts513-// shared/counter-store-creator.ts514-import { type StateCreator } from 'zustand'515-516-export type CounterStore = {517- count: number518- inc: () => void519-}520-521-export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({522- count: 1,523- inc: () => set((state) => ({ count: state.count + 1 })),524-})525-```526-527-```ts528-// stores/use-counter-store.ts529-import { create } from 'zustand'530-531-import {532- type CounterStore,533- counterStoreCreator,534-} from '../shared/counter-store-creator'535-536-export const useCounterStore = create<CounterStore>()(counterStoreCreator)537-```538-539-```tsx540-// contexts/use-counter-store-context.tsx541-import { type ReactNode, createContext, useContext, useState } from 'react'542-import { createStore } from 'zustand'543-import { useStoreWithEqualityFn } from 'zustand/traditional'544-import { shallow } from 'zustand/shallow'545-546-import {547- type CounterStore,548- counterStoreCreator,549-} from '../shared/counter-store-creator'550-551-export const createCounterStore = () => {552- return createStore<CounterStore>(counterStoreCreator)553-}554-555-export type CounterStoreApi = ReturnType<typeof createCounterStore>556-557-export const CounterStoreContext = createContext<CounterStoreApi | undefined>(558- undefined,559-)560-561-export interface CounterStoreProviderProps {562- children: ReactNode563-}564-565-export const CounterStoreProvider = ({566- children,567-}: CounterStoreProviderProps) => {568- const [store] = useState(() => createCounterStore())569- return (570- <CounterStoreContext.Provider value={store}>571- {children}572- </CounterStoreContext.Provider>573- )574-}575-576-export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T577-578-export const useCounterStoreContext = <T,>(579- selector: UseCounterStoreContextSelector<T>,580-): T => {581- const counterStoreContext = useContext(CounterStoreContext)582-583- if (counterStoreContext === undefined) {584- throw new Error(585- 'useCounterStoreContext must be used within CounterStoreProvider',586- )587- }588-589- return useStoreWithEqualityFn(counterStoreContext, selector, shallow)590-}591-```592-593-```tsx594-// components/counter/counter.tsx595-import { useCounterStore } from '../../stores/use-counter-store'596-597-export function Counter() {598- const { count, inc } = useCounterStore()599-600- return (601- <div>602- <h2>Counter Store</h2>603- <h4>{count}</h4>604- <button onClick={inc}>One Up</button>605- </div>606- )607-}608-```609-610-```ts611-// components/counter/index.ts612-export * from './counter'613-```614-615-```tsx616-// components/counter/counter.test.tsx617-import { act, render, screen } from '@testing-library/react'618-import userEvent from '@testing-library/user-event'619-620-import { Counter, useCounterStore } from '../../../stores/use-counter-store.ts'621-622-describe('Counter', () => {623- test('should render with initial state of 1', async () => {624- renderCounter()625-626- expect(useCounterStore.getState().count).toBe(1)627- })628-629- test('should increase count by clicking a button', async () => {630- const user = userEvent.setup()631-632- renderCounter()633-634- expect(useCounterStore.getState().count).toBe(1)635-636- await user.click(await screen.findByRole('button', { name: /one up/i }))637-638- expect(useCounterStore.getState().count).toBe(2)639- })640-})641-642-const renderCounter = () => {643- return render(<Counter />)644-}645-```646-647-```tsx648-// components/counter-with-context/counter-with-context.tsx649-import {650- CounterStoreProvider,651- useCounterStoreContext,652-} from '../../contexts/use-counter-store-context'653-654-const Counter = () => {655- const { count, inc } = useCounterStoreContext((state) => state)656-657- return (658- <div>659- <h2>Counter Store Context</h2>660- <h4>{count}</h4>661- <button onClick={inc}>One Up</button>662- </div>663- )664-}665-666-export const CounterWithContext = () => {667- return (668- <CounterStoreProvider>669- <Counter />670- </CounterStoreProvider>671- )672-}673-```674-675-```tsx676-// components/counter-with-context/index.ts677-export * from './counter-with-context'678-```679-680-```tsx681-// components/counter-with-context/counter-with-context.test.tsx682-import { act, render, screen } from '@testing-library/react'683-import userEvent from '@testing-library/user-event'684-685-import { CounterStoreContext } from '../../../contexts/use-counter-store-context'686-import { counterStoreCreator } from '../../../shared/counter-store-creator'687-688-describe('CounterWithContext', () => {689- test('should render with initial state of 1', async () => {690- const counterStore = counterStoreCreator()691-692- renderCounterWithContext(counterStore)693-694- expect(counterStore.getState().count).toBe(1)695- expect(696- await screen.findByRole('button', { name: /one up/i }),697- ).toBeInTheDocument()698- })699-700- test('should increase count by clicking a button', async () => {701- const user = userEvent.setup()702- const counterStore = counterStoreCreator()703-704- renderCounterWithContext(counterStore)705-706- expect(counterStore.getState().count).toBe(1)707-708- await user.click(await screen.findByRole('button', { name: /one up/i }))709-710- expect(counterStore.getState().count).toBe(2)711- })712-})713-714-const renderCounterWithContext = (store) => {715- return render(<CounterWithContext />, {716- wrapper: ({ children }) => (717- <CounterStoreContext.Provider value={store}>718- {children}719- </CounterStoreContext.Provider>720- ),721- })722-}723-```724-725-## References726-727-- **React Testing Library**: [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)728- is a very lightweight solution for testing React components. It provides utility functions on top729- of `react-dom` and `react-dom/test-utils`, in a way that encourages better testing practices. Its730- primary guiding principle is: "The more your tests resemble the way your software is used, the731- more confidence they can give you."732-- **Native Testing Library**: [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)733- is a very lightweight solution for testing React Native components, similarly to RTL, but its734- functions are built on top of `react-test-renderer`.735-- **Testing Implementation Details**: Blog post by Kent C. Dodds on why he recommends to avoid736- [testing implementation details](https://kentcdodds.com/blog/testing-implementation-details).737-738-## Demos739-740-- Jest: https://stackblitz.com/edit/jest-zustand741-- Vitest: https://stackblitz.com/edit/vitest-zustanddeleted:docs/guides/tutorial-tic-tac-toe.md-1429 removed
1----2-title: 'Tutorial: Tic-Tac-Toe'3-description: Building a game4-nav: 15----6-7-# Tutorial: Tic-Tac-Toe8-9-## Building a game10-11-You will build a small tic-tac-toe game during this tutorial. This tutorial does assume existing12-React knowledge. The techniques you'll learn in the tutorial are fundamental to building any React13-app, and fully understanding it will give you a deep understanding of React and Zustand.14-15-> [!NOTE]16-> This tutorial is crafted for those who learn best through hands-on experience and want to swiftly17-> create something tangible. It draws inspiration from React's tic-tac-toe tutorial.18-19-The tutorial is divided into several sections:20-21-- Setup for the tutorial will give you a starting point to follow the tutorial.22-- Overview will teach you the fundamentals of React: components, props, and state.23-- Completing the game will teach you the most common techniques in React development.24-- Adding time travel will give you a deeper insight into the unique strengths of React.25-26-### What are you building?27-28-In this tutorial, you'll build an interactive tic-tac-toe game with React and Zustand.29-30-You can see what it will look like when you're finished here:31-32-```jsx33-import { create } from 'zustand'34-import { combine } from 'zustand/middleware'35-36-const useGameStore = create(37- combine(38- {39- history: [Array(9).fill(null)],40- currentMove: 0,41- },42- (set, get) => {43- return {44- setHistory: (nextHistory) => {45- set((state) => ({46- history:47- typeof nextHistory === 'function'48- ? nextHistory(state.history)49- : nextHistory,50- }))51- },52- setCurrentMove: (nextCurrentMove) => {53- set((state) => ({54- currentMove:55- typeof nextCurrentMove === 'function'56- ? nextCurrentMove(state.currentMove)57- : nextCurrentMove,58- }))59- },60- }61- },62- ),63-)64-65-function Square({ value, onSquareClick }) {66- return (67- <button68- style={{69- display: 'inline-flex',70- alignItems: 'center',71- justifyContent: 'center',72- padding: 0,73- backgroundColor: '#fff',74- border: '1px solid #999',75- outline: 0,76- borderRadius: 0,77- fontSize: '1rem',78- fontWeight: 'bold',79- }}80- onClick={onSquareClick}81- >82- {value}83- </button>84- )85-}86-87-function Board({ xIsNext, squares, onPlay }) {88- const winner = calculateWinner(squares)89- const turns = calculateTurns(squares)90- const player = xIsNext ? 'X' : 'O'91- const status = calculateStatus(winner, turns, player)92-93- function handleClick(i) {94- if (squares[i] || winner) return95- const nextSquares = squares.slice()96- nextSquares[i] = player97- onPlay(nextSquares)98- }99-100- return (101- <>102- <div style={{ marginBottom: '0.5rem' }}>{status}</div>103- <div104- style={{105- display: 'grid',106- gridTemplateColumns: 'repeat(3, 1fr)',107- gridTemplateRows: 'repeat(3, 1fr)',108- width: 'calc(3 * 2.5rem)',109- height: 'calc(3 * 2.5rem)',110- border: '1px solid #999',111- }}112- >113- {squares.map((_, i) => (114- <Square115- key={`square-${i}`}116- value={squares[i]}117- onSquareClick={() => handleClick(i)}118- />119- ))}120- </div>121- </>122- )123-}124-125-export default function Game() {126- const history = useGameStore((state) => state.history)127- const setHistory = useGameStore((state) => state.setHistory)128- const currentMove = useGameStore((state) => state.currentMove)129- const setCurrentMove = useGameStore((state) => state.setCurrentMove)130- const xIsNext = currentMove % 2 === 0131- const currentSquares = history[currentMove]132-133- function handlePlay(nextSquares) {134- const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]135- setHistory(nextHistory)136- setCurrentMove(nextHistory.length - 1)137- }138-139- function jumpTo(nextMove) {140- setCurrentMove(nextMove)141- }142-143- return (144- <div145- style={{146- display: 'flex',147- flexDirection: 'row',148- fontFamily: 'monospace',149- }}150- >151- <div>152- <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />153- </div>154- <div style={{ marginLeft: '1rem' }}>155- <ol>156- {history.map((_, historyIndex) => {157- const description =158- historyIndex > 0159- ? `Go to move #${historyIndex}`160- : 'Go to game start'161-162- return (163- <li key={historyIndex}>164- <button onClick={() => jumpTo(historyIndex)}>165- {description}166- </button>167- </li>168- )169- })}170- </ol>171- </div>172- </div>173- )174-}175-176-function calculateWinner(squares) {177- const lines = [178- [0, 1, 2],179- [3, 4, 5],180- [6, 7, 8],181- [0, 3, 6],182- [1, 4, 7],183- [2, 5, 8],184- [0, 4, 8],185- [2, 4, 6],186- ]187-188- for (let i = 0; i < lines.length; i++) {189- const [a, b, c] = lines[i]190- if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {191- return squares[a]192- }193- }194-195- return null196-}197-198-function calculateTurns(squares) {199- return squares.filter((square) => !square).length200-}201-202-function calculateStatus(winner, turns, player) {203- if (!winner && !turns) return 'Draw'204- if (winner) return `Winner ${winner}`205- return `Next player: ${player}`206-}207-```208-209-### Building the board210-211-Let's start by creating the `Square` component, which will be a building block for our `Board`212-component. This component will represent each square in our game.213-214-The `Square` component should take `value` and `onSquareClick` as props. It should return a215-`<button>` element, styled to look like a square. The button displays the value prop, which can be216-`'X'`, `'O'`, or `null`, depending on the game's state. When the button is clicked, it triggers the217-`onSquareClick` function passed in as a prop, allowing the game to respond to user input.218-219-Here's the code for the `Square` component:220-221-```jsx222-function Square({ value, onSquareClick }) {223- return (224- <button225- style={{226- display: 'inline-flex',227- alignItems: 'center',228- justifyContent: 'center',229- padding: 0,230- backgroundColor: '#fff',231- border: '1px solid #999',232- outline: 0,233- borderRadius: 0,234- fontSize: '1rem',235- fontWeight: 'bold',236- }}237- onClick={onSquareClick}238- >239- {value}240- </button>241- )242-}243-```244-245-Let's move on to creating the Board component, which will consist of 9 squares arranged in a grid.246-This component will serve as the main playing area for our game.247-248-The `Board` component should return a `<div>` element styled as a grid. The grid layout is achieved249-using CSS Grid, with three columns and three rows, each taking up an equal fraction of the available250-space. The overall size of the grid is determined by the width and height properties, ensuring that251-it is square-shaped and appropriately sized.252-253-Inside the grid, we place nine Square components, each with a value prop representing its position.254-These Square components will eventually hold the game symbols (`'X'` or `'O'`) and handle user255-interactions.256-257-Here's the code for the `Board` component:258-259-```jsx260-export default function Board() {261- return (262- <div263- style={{264- display: 'grid',265- gridTemplateColumns: 'repeat(3, 1fr)',266- gridTemplateRows: 'repeat(3, 1fr)',267- width: 'calc(3 * 2.5rem)',268- height: 'calc(3 * 2.5rem)',269- border: '1px solid #999',270- }}271- >272- <Square value="1" />273- <Square value="2" />274- <Square value="3" />275- <Square value="4" />276- <Square value="5" />277- <Square value="6" />278- <Square value="7" />279- <Square value="8" />280- <Square value="9" />281- </div>282- )283-}284-```285-286-This Board component sets up the basic structure for our game board by arranging nine squares in a287-3x3 grid. It positions the squares neatly, providing a foundation for adding more features and288-handling player interactions in the future.289-290-### Lifting state up291-292-Each `Square` component could maintain a part of the game's state. To check for a winner in a293-tic-tac-toe game, the `Board` component would need to somehow know the state of each of the 9294-`Square` components.295-296-How would you approach that? At first, you might guess that the `Board` component needs to ask each297-`Square` component for that `Square`'s component state. Although this approach is technically298-possible in React, we discourage it because the code becomes difficult to understand, susceptible299-to bugs, and hard to refactor. Instead, the best approach is to store the game's state in the300-parent `Board` component instead of in each `Square` component. The `Board` component can tell each301-`Square` component what to display by passing a prop, like you did when you passed a number to each302-`Square` component.303-304-> [!IMPORTANT]305-> To collect data from multiple children, or to have two or more child components306-> communicate with each other, declare the shared state in their parent component instead. The307-> parent component can pass that state back down to the children via props. This keeps the child308-> components in sync with each other and with their parent.309-310-Let's take this opportunity to try it out. Edit the `Board` component so that it declares a state311-variable named squares that defaults to an array of 9 nulls corresponding to the 9 squares:312-313-```jsx314-import { create } from 'zustand'315-import { combine } from 'zustand/middleware'316-317-const useGameStore = create(318- combine({ squares: Array(9).fill(null) }, (set) => {319- return {320- setSquares: (nextSquares) => {321- set((state) => ({322- squares:323- typeof nextSquares === 'function'324- ? nextSquares(state.squares)325- : nextSquares,326- }))327- },328- }329- }),330-)331-332-export default function Board() {333- const squares = useGameStore((state) => state.squares)334- const setSquares = useGameStore((state) => state.setSquares)335-336- return (337- <div338- style={{339- display: 'grid',340- gridTemplateColumns: 'repeat(3, 1fr)',341- gridTemplateRows: 'repeat(3, 1fr)',342- width: 'calc(3 * 2.5rem)',343- height: 'calc(3 * 2.5rem)',344- border: '1px solid #999',345- }}346- >347- {squares.map((square, squareIndex) => (348- <Square key={squareIndex} value={square} />349- ))}350- </div>351- )352-}353-```354-355-`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The356-`useGameStore` declares a `squares` state that's initially set to that array. Each entry in the357-array corresponds to the value of a square. When you fill the board in later, the squares array358-will look like this:359-360-```js361-const squares = ['O', null, 'X', 'X', 'X', 'O', 'O', null, null]362-```363-364-Each Square will now receive a `value` prop that will either be `'X'`, `'O'`, or `null` for empty365-squares.366-367-Next, you need to change what happens when a `Square` component is clicked. The `Board` component368-now maintains which squares are filled. You'll need to create a way for the `Square` component to369-update the `Board`'s component state. Since state is private to a component that defines it, you370-cannot update the `Board`'s component state directly from `Square` component.371-372-Instead, you'll pass down a function from the Board component to the `Square` component, and you'll373-have `Square` component call that function when a square is clicked. You'll start with the function374-that the `Square` component will call when it is clicked. You'll call that function `onSquareClick`:375-376-Now you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name377-`handleClick`. To connect `onSquareClick` to `handleClick` you'll pass an inline function to the378-`onSquareClick` prop of the first Square component:379-380-```jsx381-<Square key={squareIndex} value={square} onSquareClick={() => handleClick(i)} />382-```383-384-Lastly, you will define the `handleClick` function inside the `Board` component to update the385-squares array holding your board's state.386-387-The `handleClick` function should take the index of the square to update and create a copy of the388-`squares` array (`nextSquares`). Then, `handleClick` updates the `nextSquares` array by adding `X`389-to the square at the specified index (`i`) if is not already filled.390-391-```jsx {5-10,27}392-export default function Board() {393- const squares = useGameStore((state) => state.squares)394- const setSquares = useGameStore((state) => state.setSquares)395-396- function handleClick(i) {397- if (squares[i]) return398- const nextSquares = squares.slice()399- nextSquares[i] = 'X'400- setSquares(nextSquares)401- }402-403- return (404- <div405- style={{406- display: 'grid',407- gridTemplateColumns: 'repeat(3, 1fr)',408- gridTemplateRows: 'repeat(3, 1fr)',409- width: 'calc(3 * 2.5rem)',410- height: 'calc(3 * 2.5rem)',411- border: '1px solid #999',412- }}413- >414- {squares.map((square, squareIndex) => (415- <Square416- key={squareIndex}417- value={square}418- onSquareClick={() => handleClick(squareIndex)}419- />420- ))}421- </div>422- )423-}424-```425-426-> [!IMPORTANT]427-> Note how in `handleClick` function, you call `.slice()` to create a copy of the squares array428-> instead of modifying the existing array.429-430-### Taking turns431-432-It's now time to fix a major defect in this tic-tac-toe game: the `'O'`s cannot be used on the433-board.434-435-You'll set the first move to be `'X'` by default. Let's keep track of this by adding another piece436-of state to the `useGameStore` hook:437-438-```jsx {2,12-18}439-const useGameStore = create(440- combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {441- return {442- setSquares: (nextSquares) => {443- set((state) => ({444- squares:445- typeof nextSquares === 'function'446- ? nextSquares(state.squares)447- : nextSquares,448- }))449- },450- setXIsNext: (nextXIsNext) => {451- set((state) => ({452- xIsNext:453- typeof nextXIsNext === 'function'454- ? nextXIsNext(state.xIsNext)455- : nextXIsNext,456- }))457- },458- }459- }),460-)461-```462-463-Each time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next464-and the game's state will be saved. You'll update the Board's `handleClick` function to flip the465-value of `xIsNext`:466-467-```jsx {2-3,6,11}468-export default function Board() {469- const xIsNext = useGameStore((state) => state.xIsNext)470- const setXIsNext = useGameStore((state) => state.setXIsNext)471- const squares = useGameStore((state) => state.squares)472- const setSquares = useGameStore((state) => state.setSquares)473- const player = xIsNext ? 'X' : 'O'474-475- function handleClick(i) {476- if (squares[i]) return477- const nextSquares = squares.slice()478- nextSquares[i] = player479- setSquares(nextSquares)480- setXIsNext(!xIsNext)481- }482-483- return (484- <div485- style={{486- display: 'grid',487- gridTemplateColumns: 'repeat(3, 1fr)',488- gridTemplateRows: 'repeat(3, 1fr)',489- width: 'calc(3 * 2.5rem)',490- height: 'calc(3 * 2.5rem)',491- border: '1px solid #999',492- }}493- >494- {squares.map((square, squareIndex) => (495- <Square496- key={squareIndex}497- value={square}498- onSquareClick={() => handleClick(squareIndex)}499- />500- ))}501- </div>502- )503-}504-```505-506-### Declaring a winner or draw507-508-Now that the players can take turns, you'll want to show when the game is won or drawn and there509-are no more turns to make. To do this you'll add three helper functions. The first helper function510-called `calculateWinner` that takes an array of 9 squares, checks for a winner and returns `'X'`,511-`'O'`, or `null` as appropriate. The second helper function called `calculateTurns` that takes the512-same array, checks for remaining turns by filtering out only `null` items, and returns the count of513-them. The last helper called `calculateStatus` that takes the remaining turns, the winner, and the514-current player (`'X' or 'O'`):515-516-```js517-function calculateWinner(squares) {518- const lines = [519- [0, 1, 2],520- [3, 4, 5],521- [6, 7, 8],522- [0, 3, 6],523- [1, 4, 7],524- [2, 5, 8],525- [0, 4, 8],526- [2, 4, 6],527- ]528-529- for (let i = 0; i < lines.length; i++) {530- const [a, b, c] = lines[i]531- if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {532- return squares[a]533- }534- }535-536- return null537-}538-539-function calculateTurns(squares) {540- return squares.filter((square) => !square).length541-}542-543-function calculateStatus(winner, turns, player) {544- if (!winner && !turns) return 'Draw'545- if (winner) return `Winner ${winner}`546- return `Next player: ${player}`547-}548-```549-550-You will use the result of `calculateWinner(squares)` in the Board component's `handleClick`551-function to check if a player has won. You can perform this check at the same time you check if a552-user has clicked a square that already has a `'X'` or and `'O'`. We'd like to return early in553-both cases:554-555-```js {2}556-function handleClick(i) {557- if (squares[i] || winner) return558- const nextSquares = squares.slice()559- nextSquares[i] = player560- setSquares(nextSquares)561- setXIsNext(!xIsNext)562-}563-```564-565-To let the players know when the game is over, you can display text such as `'Winner: X'` or566-`'Winner: O'`. To do that you'll add a `status` section to the `Board` component. The status will567-display the winner or draw if the game is over and if the game is ongoing you'll display which568-player's turn is next:569-570-```jsx {6-7,9,21}571-export default function Board() {572- const xIsNext = useGameStore((state) => state.xIsNext)573- const setXIsNext = useGameStore((state) => state.setXIsNext)574- const squares = useGameStore((state) => state.squares)575- const setSquares = useGameStore((state) => state.setSquares)576- const winner = calculateWinner(squares)577- const turns = calculateTurns(squares)578- const player = xIsNext ? 'X' : 'O'579- const status = calculateStatus(winner, turns, player)580-581- function handleClick(i) {582- if (squares[i] || winner) return583- const nextSquares = squares.slice()584- nextSquares[i] = player585- setSquares(nextSquares)586- setXIsNext(!xIsNext)587- }588-589- return (590- <>591- <div style={{ marginBottom: '0.5rem' }}>{status}</div>592- <div593- style={{594- display: 'grid',595- gridTemplateColumns: 'repeat(3, 1fr)',596- gridTemplateRows: 'repeat(3, 1fr)',597- width: 'calc(3 * 2.5rem)',598- height: 'calc(3 * 2.5rem)',599- border: '1px solid #999',600- }}601- >602- {squares.map((square, squareIndex) => (603- <Square604- key={squareIndex}605- value={square}606- onSquareClick={() => handleClick(squareIndex)}607- />608- ))}609- </div>610- </>611- )612-}613-```614-615-Congratulations! You now have a working tic-tac-toe game. And you've just learned the basics of616-React and Zustand too. So you are the real winner here. Here is what the code should look like:617-618-```jsx619-import { create } from 'zustand'620-import { combine } from 'zustand/middleware'621-622-const useGameStore = create(623- combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {624- return {625- setSquares: (nextSquares) => {626- set((state) => ({627- squares:628- typeof nextSquares === 'function'629- ? nextSquares(state.squares)630- : nextSquares,631- }))632- },633- setXIsNext: (nextXIsNext) => {634- set((state) => ({635- xIsNext:636- typeof nextXIsNext === 'function'637- ? nextXIsNext(state.xIsNext)638- : nextXIsNext,639- }))640- },641- }642- }),643-)644-645-function Square({ value, onSquareClick }) {646- return (647- <button648- style={{649- display: 'inline-flex',650- alignItems: 'center',651- justifyContent: 'center',652- padding: 0,653- backgroundColor: '#fff',654- border: '1px solid #999',655- outline: 0,656- borderRadius: 0,657- fontSize: '1rem',658- fontWeight: 'bold',659- }}660- onClick={onSquareClick}661- >662- {value}663- </button>664- )665-}666-667-export default function Board() {668- const xIsNext = useGameStore((state) => state.xIsNext)669- const setXIsNext = useGameStore((state) => state.setXIsNext)670- const squares = useGameStore((state) => state.squares)671- const setSquares = useGameStore((state) => state.setSquares)672- const winner = calculateWinner(squares)673- const turns = calculateTurns(squares)674- const player = xIsNext ? 'X' : 'O'675- const status = calculateStatus(winner, turns, player)676-677- function handleClick(i) {678- if (squares[i] || winner) return679- const nextSquares = squares.slice()680- nextSquares[i] = player681- setSquares(nextSquares)682- setXIsNext(!xIsNext)683- }684-685- return (686- <>687- <div style={{ marginBottom: '0.5rem' }}>{status}</div>688- <div689- style={{690- display: 'grid',691- gridTemplateColumns: 'repeat(3, 1fr)',692- gridTemplateRows: 'repeat(3, 1fr)',693- width: 'calc(3 * 2.5rem)',694- height: 'calc(3 * 2.5rem)',695- border: '1px solid #999',696- }}697- >698- {squares.map((square, squareIndex) => (699- <Square700- key={squareIndex}701- value={square}702- onSquareClick={() => handleClick(squareIndex)}703- />704- ))}705- </div>706- </>707- )708-}709-710-function calculateWinner(squares) {711- const lines = [712- [0, 1, 2],713- [3, 4, 5],714- [6, 7, 8],715- [0, 3, 6],716- [1, 4, 7],717- [2, 5, 8],718- [0, 4, 8],719- [2, 4, 6],720- ]721-722- for (let i = 0; i < lines.length; i++) {723- const [a, b, c] = lines[i]724- if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {725- return squares[a]726- }727- }728-729- return null730-}731-732-function calculateTurns(squares) {733- return squares.filter((square) => !square).length734-}735-736-function calculateStatus(winner, turns, player) {737- if (!winner && !turns) return 'Draw'738- if (winner) return `Winner ${winner}`739- return `Next player: ${player}`740-}741-```742-743-### Adding time travel744-745-As a final exercise, let's make it possible to “go back in time” and revisit previous moves in the746-game.747-748-If you had directly modified the squares array, implementing this time-travel feature would be very749-difficult. However, since you used `slice()` to create a new copy of the squares array after every750-move, treating it as immutable, you can store every past version of the squares array and navigate751-between them.752-753-You'll keep track of these past squares arrays in a new state variable called `history`. This754-`history` array will store all board states, from the first move to the latest one, and will look755-something like this:756-757-```js758-const history = [759- // First move760- [null, null, null, null, null, null, null, null, null],761- // Second move762- ['X', null, null, null, null, null, null, null, null],763- // Third move764- ['X', 'O', null, null, null, null, null, null, null],765- // and so on...766-]767-```768-769-This approach allows you to easily navigate between different game states and implement the770-time-travel feature.771-772-### Lifting state up, again773-774-Next, you will create a new top-level component called `Game` to display a list of past moves. This775-is where you will store the `history` state that contains the entire game history.776-777-By placing the `history` state in the `Game` component, you can remove the `squares` state from the778-`Board` component. You will now lift the state up from the `Board` component to the top-level `Game`779-component. This change allows the `Game` component to have full control over the `Board`'s780-component data and instruct the `Board` component to render previous turns from the `history`.781-782-First, add a `Game` component with `export default` and remove it from `Board` component. Here is783-what the code should look like:784-785-```jsx {1,44-61}786-function Board() {787- const xIsNext = useGameStore((state) => state.xIsNext)788- const setXIsNext = useGameStore((state) => state.setXIsNext)789- const squares = useGameStore((state) => state.squares)790- const setSquares = useGameStore((state) => state.setSquares)791- const winner = calculateWinner(squares)792- const turns = calculateTurns(squares)793- const player = xIsNext ? 'X' : 'O'794- const status = calculateStatus(winner, turns, player)795-796- function handleClick(i) {797- if (squares[i] || winner) return798- const nextSquares = squares.slice()799- nextSquares[i] = player800- setSquares(nextSquares)801- setXIsNext(!xIsNext)802- }803-804- return (805- <>806- <div style={{ marginBottom: '0.5rem' }}>{status}</div>807- <div808- style={{809- display: 'grid',810- gridTemplateColumns: 'repeat(3, 1fr)',811- gridTemplateRows: 'repeat(3, 1fr)',812- width: 'calc(3 * 2.5rem)',813- height: 'calc(3 * 2.5rem)',814- border: '1px solid #999',815- }}816- >817- {squares.map((square, squareIndex) => (818- <Square819- key={squareIndex}820- value={square}821- onSquareClick={() => handleClick(squareIndex)}822- />823- ))}824- </div>825- </>826- )827-}828-829-export default function Game() {830- return (831- <div832- style={{833- display: 'flex',834- flexDirection: 'row',835- fontFamily: 'monospace',836- }}837- >838- <div>839- <Board />840- </div>841- <div style={{ marginLeft: '1rem' }}>842- <ol>{/* TODO */}</ol>843- </div>844- </div>845- )846-}847-```848-849-Add some state to the `useGameStore` hook to track the history of moves:850-851-```js {2,4-11}852-const useGameStore = create(853- combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {854- return {855- setHistory: (nextHistory) => {856- set((state) => ({857- history:858- typeof nextHistory === 'function'859- ? nextHistory(state.history)860- : nextHistory,861- }))862- },863- setXIsNext: (nextXIsNext) => {864- set((state) => ({865- xIsNext:866- typeof nextXIsNext === 'function'867- ? nextXIsNext(state.xIsNext)868- : nextXIsNext,869- }))870- },871- }872- }),873-)874-```875-876-Notice how `[Array(9).fill(null)]` creates an array with a single item, which is itself an array of877-9 null values.878-879-To render the squares for the current move, you'll need to read the most recent squares array from880-the `history` state. You don't need an extra state for this because you already have enough881-information to calculate it during rendering:882-883-```jsx {2-6}884-export default function Game() {885- const history = useGameStore((state) => state.history)886- const setHistory = useGameStore((state) => state.setHistory)887- const xIsNext = useGameStore((state) => state.xIsNext)888- const setXIsNext = useGameStore((state) => state.setXIsNext)889- const currentSquares = history[history.length - 1]890-891- return (892- <div893- style={{894- display: 'flex',895- flexDirection: 'row',896- fontFamily: 'monospace',897- }}898- >899- <div>900- <Board />901- </div>902- <div style={{ marginLeft: '1rem' }}>903- <ol>{/*TODO*/}</ol>904- </div>905- </div>906- )907-}908-```909-910-Next, create a `handlePlay` function inside the `Game` component that will be called by the `Board`911-component to update the game. Pass `xIsNext`, `currentSquares` and `handlePlay` as props to the912-`Board` component:913-914-```jsx {8-10,21}915-export default function Game() {916- const history = useGameStore((state) => state.history)917- const setHistory = useGameStore((state) => state.setHistory)918- const xIsNext = useGameStore((state) => state.xIsNext)919- const setXIsNext = useGameStore((state) => state.setXIsNext)920- const currentSquares = history[history.length - 1]921-922- function handlePlay(nextSquares) {923- // TODO924- }925-926- return (927- <div928- style={{929- display: 'flex',930- flexDirection: 'row',931- fontFamily: 'monospace',932- }}933- >934- <div>935- <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />936- </div>937- <div style={{ marginLeft: '1rem' }}>938- <ol>{/*TODO*/}</ol>939- </div>940- </div>941- )942-}943-```944-945-Let's make the `Board` component fully controlled by the props it receives. To do this, we'll modify946-the `Board` component to accept three props: `xIsNext`, `squares`, and a new `onPlay` function that947-the `Board` component can call with the updated squares array when a player makes a move.948-949-```jsx {1}950-function Board({ xIsNext, squares, onPlay }) {951- const winner = calculateWinner(squares)952- const turns = calculateTurns(squares)953- const player = xIsNext ? 'X' : 'O'954- const status = calculateStatus(winner, turns, player)955-956- function handleClick(i) {957- if (squares[i] || winner) return958- const nextSquares = squares.slice()959- nextSquares[i] = player960- onPlay(nextSquares)961- }962-963- return (964- <>965- <div style={{ marginBottom: '0.5rem' }}>{status}</div>966- <div967- style={{968- display: 'grid',969- gridTemplateColumns: 'repeat(3, 1fr)',970- gridTemplateRows: 'repeat(3, 1fr)',971- width: 'calc(3 * 2.5rem)',972- height: 'calc(3 * 2.5rem)',973- border: '1px solid #999',974- }}975- >976- {squares.map((square, squareIndex) => (977- <Square978- key={squareIndex}979- value={square}980- onSquareClick={() => handleClick(squareIndex)}981- />982- ))}983- </div>984- </>985- )986-}987-```988-989-The `Board` component is now fully controlled by the props passed to it by the `Game` component. To990-get the game working again, you need to implement the `handlePlay` function in the `Game`991-component.992-993-What should `handlePlay` do when called? Previously, the `Board` component called `setSquares` with994-an updated array; now it passes the updated squares array to `onPlay`.995-996-The `handlePlay` function needs to update the `Game` component's state to trigger a re-render.997-Instead of using `setSquares`, you'll update the `history` state variable by appending the updated998-squares array as a new `history` entry. You also need to toggle `xIsNext`, just as the `Board`999-component used1000-to do.1001-1002-```js {2-3}1003-function handlePlay(nextSquares) {1004- setHistory(history.concat([nextSquares]))1005- setXIsNext(!xIsNext)1006-}1007-```1008-1009-At this point, you've moved the state to live in the `Game` component, and the UI should be fully1010-working, just as it was before the refactor. Here is what the code should look like at this point:1011-1012-```jsx1013-import { create } from 'zustand'1014-import { combine } from 'zustand/middleware'1015-1016-const useGameStore = create(1017- combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {1018- return {1019- setHistory: (nextHistory) => {1020- set((state) => ({1021- history:1022- typeof nextHistory === 'function'1023- ? nextHistory(state.history)1024- : nextHistory,1025- }))1026- },1027- setXIsNext: (nextXIsNext) => {1028- set((state) => ({1029- xIsNext:1030- typeof nextXIsNext === 'function'1031- ? nextXIsNext(state.xIsNext)1032- : nextXIsNext,1033- }))1034- },1035- }1036- }),1037-)1038-1039-function Square({ value, onSquareClick }) {1040- return (1041- <button1042- style={{1043- display: 'inline-flex',1044- alignItems: 'center',1045- justifyContent: 'center',1046- padding: 0,1047- backgroundColor: '#fff',1048- border: '1px solid #999',1049- outline: 0,1050- borderRadius: 0,1051- fontSize: '1rem',1052- fontWeight: 'bold',1053- }}1054- onClick={onSquareClick}1055- >1056- {value}1057- </button>1058- )1059-}1060-1061-function Board({ xIsNext, squares, onPlay }) {1062- const winner = calculateWinner(squares)1063- const turns = calculateTurns(squares)1064- const player = xIsNext ? 'X' : 'O'1065- const status = calculateStatus(winner, turns, player)1066-1067- function handleClick(i) {1068- if (squares[i] || winner) return1069- const nextSquares = squares.slice()1070- nextSquares[i] = player1071- onPlay(nextSquares)1072- }1073-1074- return (1075- <>1076- <div style={{ marginBottom: '0.5rem' }}>{status}</div>1077- <div1078- style={{1079- display: 'grid',1080- gridTemplateColumns: 'repeat(3, 1fr)',1081- gridTemplateRows: 'repeat(3, 1fr)',1082- width: 'calc(3 * 2.5rem)',1083- height: 'calc(3 * 2.5rem)',1084- border: '1px solid #999',1085- }}1086- >1087- {squares.map((square, squareIndex) => (1088- <Square1089- key={squareIndex}1090- value={square}1091- onSquareClick={() => handleClick(squareIndex)}1092- />1093- ))}1094- </div>1095- </>1096- )1097-}1098-1099-export default function Game() {1100- const history = useGameStore((state) => state.history)1101- const setHistory = useGameStore((state) => state.setHistory)1102- const xIsNext = useGameStore((state) => state.xIsNext)1103- const setXIsNext = useGameStore((state) => state.setXIsNext)1104- const currentSquares = history[history.length - 1]1105-1106- function handlePlay(nextSquares) {1107- setHistory(history.concat([nextSquares]))1108- setXIsNext(!xIsNext)1109- }1110-1111- return (1112- <div1113- style={{1114- display: 'flex',1115- flexDirection: 'row',1116- fontFamily: 'monospace',1117- }}1118- >1119- <div>1120- <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1121- </div>1122- <div style={{ marginLeft: '1rem' }}>1123- <ol>{/*TODO*/}</ol>1124- </div>1125- </div>1126- )1127-}1128-1129-function calculateWinner(squares) {1130- const lines = [1131- [0, 1, 2],1132- [3, 4, 5],1133- [6, 7, 8],1134- [0, 3, 6],1135- [1, 4, 7],1136- [2, 5, 8],1137- [0, 4, 8],1138- [2, 4, 6],1139- ]1140-1141- for (let i = 0; i < lines.length; i++) {1142- const [a, b, c] = lines[i]1143- if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {1144- return squares[a]1145- }1146- }1147-1148- return null1149-}1150-1151-function calculateTurns(squares) {1152- return squares.filter((square) => !square).length1153-}1154-1155-function calculateStatus(winner, turns, player) {1156- if (!winner && !turns) return 'Draw'1157- if (winner) return `Winner ${winner}`1158- return `Next player: ${player}`1159-}1160-```1161-1162-### Showing the past moves1163-1164-Since you are recording the tic-tac-toe game's history, you can now display a list of past moves to1165-the player.1166-1167-You already have an array of `history` moves in store, so now you need to transform it to an array1168-of React elements. In JavaScript, to transform one array into another, you can use the Array1169-`.map()` method:1170-1171-You'll use `map` to transform your `history` of moves into React elements representing buttons on the1172-screen, and display a list of buttons to **jump** to past moves. Let's `map` over the `history` in1173-the `Game` component:1174-1175-```jsx {29-44}1176-export default function Game() {1177- const history = useGameStore((state) => state.history)1178- const setHistory = useGameStore((state) => state.setHistory)1179- const xIsNext = useGameStore((state) => state.xIsNext)1180- const setXIsNext = useGameStore((state) => state.setXIsNext)1181- const currentSquares = history[history.length - 1]1182-1183- function handlePlay(nextSquares) {1184- setHistory(history.concat([nextSquares]))1185- setXIsNext(!xIsNext)1186- }1187-1188- function jumpTo(nextMove) {1189- // TODO1190- }1191-1192- return (1193- <div1194- style={{1195- display: 'flex',1196- flexDirection: 'row',1197- fontFamily: 'monospace',1198- }}1199- >1200- <div>1201- <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1202- </div>1203- <div style={{ marginLeft: '1rem' }}>1204- <ol>1205- {history.map((_, historyIndex) => {1206- const description =1207- historyIndex > 01208- ? `Go to move #${historyIndex}`1209- : 'Go to game start'1210-1211- return (1212- <li key={historyIndex}>1213- <button onClick={() => jumpTo(historyIndex)}>1214- {description}1215- </button>1216- </li>1217- )1218- })}1219- </ol>1220- </div>1221- </div>1222- )1223-}1224-```1225-1226-Before you can implement the `jumpTo` function, you need the `Game` component to keep track of which1227-step the user is currently viewing. To do this, define a new state variable called `currentMove`,1228-which will start at `0`:1229-1230-```js {3,14-21}1231-const useGameStore = create(1232- combine(1233- { history: [Array(9).fill(null)], currentMove: 0, xIsNext: true },1234- (set) => {1235- return {1236- setHistory: (nextHistory) => {1237- set((state) => ({1238- history:1239- typeof nextHistory === 'function'1240- ? nextHistory(state.history)1241- : nextHistory,1242- }))1243- },1244- setCurrentMove: (nextCurrentMove) => {1245- set((state) => ({1246- currentMove:1247- typeof nextCurrentMove === 'function'1248- ? nextCurrentMove(state.currentMove)1249- : nextCurrentMove,1250- }))1251- },1252- setXIsNext: (nextXIsNext) => {1253- set((state) => ({1254- xIsNext:1255- typeof nextXIsNext === 'function'1256- ? nextXIsNext(state.xIsNext)1257- : nextXIsNext,1258- }))1259- },1260- }1261- },1262- ),1263-)1264-```1265-1266-Next, update the `jumpTo` function inside `Game` component to update that `currentMove`. You’ll1267-also set `xIsNext` to `true` if the number that you’re changing `currentMove` to is even.1268-1269-```js {2-3}1270-function jumpTo(nextMove) {1271- setCurrentMove(nextMove)1272- setXIsNext(currentMove % 2 === 0)1273-}1274-```1275-1276-You will now make two changes to the `handlePlay` function in the `Game` component, which is called1277-when you click on a square.1278-1279-- If you "go back in time" and then make a new move from that point, you only want to keep the1280- history up to that point. Instead of adding `nextSquares` after all items in the history (using1281- the Array `.concat()` method), you'll add it after all items in1282- `history.slice(0, currentMove + 1)` to keep only that portion of the old history.1283-- Each time a move is made, you need to update `currentMove` to point to the latest history entry.1284-1285-```js {2-4}1286-function handlePlay(nextSquares) {1287- const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1288- setHistory(nextHistory)1289- setCurrentMove(nextHistory.length - 1)1290- setXIsNext(!xIsNext)1291-}1292-```1293-1294-Finally, you will modify the `Game` component to render the currently selected move, instead of1295-always rendering the final move:1296-1297-```jsx {2-8}1298-export default function Game() {1299- const history = useGameStore((state) => state.history)1300- const setHistory = useGameStore((state) => state.setHistory)1301- const currentMove = useGameStore((state) => state.currentMove)1302- const setCurrentMove = useGameStore((state) => state.setCurrentMove)1303- const xIsNext = useGameStore((state) => state.xIsNext)1304- const setXIsNext = useGameStore((state) => state.setXIsNext)1305- const currentSquares = history[currentMove]1306-1307- function handlePlay(nextSquares) {1308- const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1309- setHistory(nextHistory)1310- setCurrentMove(nextHistory.length - 1)1311- setXIsNext(!xIsNext)1312- }1313-1314- function jumpTo(nextMove) {1315- setCurrentMove(nextMove)1316- setXIsNext(nextMove % 2 === 0)1317- }1318-1319- return (1320- <div1321- style={{1322- display: 'flex',1323- flexDirection: 'row',1324- fontFamily: 'monospace',1325- }}1326- >1327- <div>1328- <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1329- </div>1330- <div style={{ marginLeft: '1rem' }}>1331- <ol>1332- {history.map((_, historyIndex) => {1333- const description =1334- historyIndex > 01335- ? `Go to move #${historyIndex}`1336- : 'Go to game start'1337-1338- return (1339- <li key={historyIndex}>1340- <button onClick={() => jumpTo(historyIndex)}>1341- {description}1342- </button>1343- </li>1344- )1345- })}1346- </ol>1347- </div>1348- </div>1349- )1350-}1351-```1352-1353-### Final cleanup1354-1355-If you look closely at the code, you'll see that `xIsNext` is `true` when `currentMove` is even and1356-`false` when `currentMove` is odd. This means that if you know the value of `currentMove`, you can1357-always determine what `xIsNext` should be.1358-1359-There's no need to store `xIsNext` separately in the state. It’s better to avoid redundant state1360-because it can reduce bugs and make your code easier to understand. Instead, you can calculate1361-`xIsNext` based on `currentMove`:1362-1363-```jsx {2-5,13,17}1364-export default function Game() {1365- const history = useGameStore((state) => state.history)1366- const setHistory = useGameStore((state) => state.setHistory)1367- const currentMove = useGameStore((state) => state.currentMove)1368- const setCurrentMove = useGameStore((state) => state.setCurrentMove)1369- const xIsNext = currentMove % 2 === 01370- const currentSquares = history[currentMove]1371-1372- function handlePlay(nextSquares) {1373- const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1374- setHistory(nextHistory)1375- setCurrentMove(nextHistory.length - 1)1376- }1377-1378- function jumpTo(nextMove) {1379- setCurrentMove(nextMove)1380- }1381-1382- return (1383- <div1384- style={{1385- display: 'flex',1386- flexDirection: 'row',1387- fontFamily: 'monospace',1388- }}1389- >1390- <div>1391- <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1392- </div>1393- <div style={{ marginLeft: '1rem' }}>1394- <ol>1395- {history.map((_, historyIndex) => {1396- const description =1397- historyIndex > 01398- ? `Go to move #${historyIndex}`1399- : 'Go to game start'1400-1401- return (1402- <li key={historyIndex}>1403- <button onClick={() => jumpTo(historyIndex)}>1404- {description}1405- </button>1406- </li>1407- )1408- })}1409- </ol>1410- </div>1411- </div>1412- )1413-}1414-```1415-1416-You no longer need the `xIsNext` state declaration or the calls to `setXIsNext`. Now, there’s no1417-chance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding1418-the components.1419-1420-### Wrapping up1421-1422-Congratulations! You’ve created a tic-tac-toe game that:1423-1424-- Lets you play tic-tac-toe,1425-- Indicates when a player has won the game or when is drawn,1426-- Stores a game’s history as a game progresses,1427-- Allows players to review a game’s history and see previous versions of a game’s board.1428-1429-Nice work! We hope you now feel like you have a decent grasp of how React and Zustand works.deleted:docs/guides/updating-state.md-141 removed
1----2-title: Updating state3-nav: 24----5-6-## Flat updates7-8-Updating state with Zustand is simple! Call the provided `set` function with9-the new state, and it will be shallowly merged with the existing state in the10-store. **Note** See next section for nested state.11-12-```tsx13-import { create } from 'zustand'14-15-type State = {16- firstName: string17- lastName: string18-}19-20-type Action = {21- updateFirstName: (firstName: State['firstName']) => void22- updateLastName: (lastName: State['lastName']) => void23-}24-25-// Create your store, which includes both state and (optionally) actions26-const usePersonStore = create<State & Action>((set) => ({27- firstName: '',28- lastName: '',29- updateFirstName: (firstName) => set(() => ({ firstName: firstName })),30- updateLastName: (lastName) => set(() => ({ lastName: lastName })),31-}))32-33-// In consuming app34-function App() {35- // "select" the needed state and actions, in this case, the firstName value36- // and the action updateFirstName37- const firstName = usePersonStore((state) => state.firstName)38- const updateFirstName = usePersonStore((state) => state.updateFirstName)39-40- return (41- <main>42- <label>43- First name44- <input45- // Update the "firstName" state46- onChange={(e) => updateFirstName(e.currentTarget.value)}47- value={firstName}48- />49- </label>50-51- <p>52- Hello, <strong>{firstName}!</strong>53- </p>54- </main>55- )56-}57-```58-59-## Deeply nested object60-61-If you have a deep state object like this:62-63-```ts64-type State = {65- deep: {66- nested: {67- obj: { count: number }68- }69- }70-}71-```72-73-Updating nested state requires some effort to ensure the process is completed74-immutably.75-76-### Normal approach77-78-Similar to React or Redux, the normal approach is to copy each level of the79-state object. This is done with the spread operator `...`, and by manually80-merging that in with the new state values. Like so:81-82-```ts83- normalInc: () =>84- set((state) => ({85- deep: {86- ...state.deep,87- nested: {88- ...state.deep.nested,89- obj: {90- ...state.deep.nested.obj,91- count: state.deep.nested.obj.count + 192- }93- }94- }95- })),96-```97-98-This is very long! Let's explore some alternatives that will make your life99-easier.100-101-### With Immer102-103-Many people use [Immer](https://github.com/immerjs/immer) to update nested104-values. Immer can be used anytime you need to update nested state such as in105-React, Redux and of course, Zustand!106-107-You can use Immer to shorten your state updates for deeply nested object. Let's108-take a look at an example:109-110-```ts111- immerInc: () =>112- set(produce((state: State) => { ++state.deep.nested.obj.count })),113-```114-115-What a reduction! Please take note of the [gotchas listed here](../integrations/immer-middleware.md).116-117-### With optics-ts118-119-There is another option with [optics-ts](https://github.com/akheron/optics-ts/):120-121-```ts122- opticsInc: () =>123- set(O.modify(O.optic<State>().path("deep.nested.obj.count"))((c) => c + 1)),124-```125-126-Unlike Immer, optics-ts doesn't use proxies or mutation syntax.127-128-### With Ramda129-130-You can also use [Ramda](https://ramdajs.com/):131-132-```ts133- ramdaInc: () =>134- set(R.modifyPath(["deep", "nested", "obj", "count"], (c) => c + 1)),135-```136-137-Both ramda and optics-ts also work with types.138-139-### Demo140-141-https://stackblitz.com/edit/vitejs-vite-j6bjdygudeleted:docs/hooks/use-shallow.md-266 removed
1----2-title: useShallow ⚛️3-description: How to memoize selector functions4-nav: 285----6-7-`useShallow` is a React Hook that lets you optimize re-renders.8-9-```js10-const memoizedSelector = useShallow(selector)11-```12-13-- [Types](#types)14- - [Signature](#signature)15-- [Reference](#reference)16-- [Usage](#usage)17- - [Writing a memoized selector](#writing-a-memoized-selector)18-- [Troubleshooting](#troubleshooting)19-20-### Signature21-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-34-#### Returns35-36-`useShallow` returns a memoized version of a selector function using a shallow comparison for37-memoization.38-39-## Usage40-41-### Writing a memoized selector42-43-First, we need to setup a store to hold the state for the bear family. In this store, we define44-three properties: `papaBear`, `mamaBear`, and `babyBear`, each representing a different member of45-the bear family and their respective oatmeal pot sizes.46-47-```tsx48-import { create } from 'zustand'49-50-type BearFamilyMealsStore = {51- [key: string]: string52-}53-54-const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({55- papaBear: 'large porridge-pot',56- mamaBear: 'middle-size porridge pot',57- babyBear: 'A little, small, wee pot',58-}))59-```60-61-Next, we'll create a `BearNames` component that retrieves the keys of our state (the bear family62-members) and displays them.63-64-```tsx65-function BearNames() {66- const names = useBearFamilyMealsStore((state) => Object.keys(state))67-68- return <div>{names.join(', ')}</div>69-}70-```71-72-Next, we will create a `UpdateBabyBearMeal` component that periodically updates baby bear's meal73-choice.74-75-```tsx76-const meals = [77- 'A tiny, little, wee bowl',78- 'A small, petite, tiny pot',79- 'A wee, itty-bitty, small bowl',80- 'A little, petite, tiny dish',81- 'A tiny, small, wee vessel',82- 'A small, little, wee cauldron',83- 'A little, tiny, small cup',84- 'A wee, small, little jar',85- 'A tiny, wee, small pan',86- 'A small, wee, little crock',87-]88-89-function UpdateBabyBearMeal() {90- useEffect(() => {91- const timer = setInterval(() => {92- useBearFamilyMealsStore.setState({93- babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],94- })95- }, 1000)96-97- return () => {98- clearInterval(timer)99- }100- }, [])101-102- return null103-}104-```105-106-Finally, we combine both components in the `App` component to see them in action.107-108-```tsx109-export default function App() {110- return (111- <>112- <UpdateBabyBearMeal />113- <BearNames />114- </>115- )116-}117-```118-119-Here is what the code should look like:120-121-```tsx122-import { useEffect } from 'react'123-import { create } from 'zustand'124-125-type BearFamilyMealsStore = {126- [key: string]: string127-}128-129-const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({130- papaBear: 'large porridge-pot',131- mamaBear: 'middle-size porridge pot',132- babyBear: 'A little, small, wee pot',133-}))134-135-const meals = [136- 'A tiny, little, wee bowl',137- 'A small, petite, tiny pot',138- 'A wee, itty-bitty, small bowl',139- 'A little, petite, tiny dish',140- 'A tiny, small, wee vessel',141- 'A small, little, wee cauldron',142- 'A little, tiny, small cup',143- 'A wee, small, little jar',144- 'A tiny, wee, small pan',145- 'A small, wee, little crock',146-]147-148-function UpdateBabyBearMeal() {149- useEffect(() => {150- const timer = setInterval(() => {151- useBearFamilyMealsStore.setState({152- babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],153- })154- }, 1000)155-156- return () => {157- clearInterval(timer)158- }159- }, [])160-161- return null162-}163-164-function BearNames() {165- const names = useBearFamilyMealsStore((state) => Object.keys(state))166-167- return <div>{names.join(', ')}</div>168-}169-170-export default function App() {171- return (172- <>173- <UpdateBabyBearMeal />174- <BearNames />175- </>176- )177-}178-```179-180-Everything might look fine, but there’s a small problem: the `BearNames` component keeps181-re-rendering even if the names haven’t changed. This happens because the component re-renders182-whenever any part of the state changes, even if the specific part we care about (the list of names) hasn’t changed.183-184-To fix this, we use `useShallow` to make sure the component only re-renders when the actual keys of185-the state change:186-187-```tsx188-function BearNames() {189- const names = useBearFamilyMealsStore(190- useShallow((state) => Object.keys(state)),191- )192-193- return <div>{names.join(', ')}</div>194-}195-```196-197-Here is what the code should look like:198-199-```tsx200-import { useEffect } from 'react'201-import { create } from 'zustand'202-import { useShallow } from 'zustand/react/shallow'203-204-type BearFamilyMealsStore = {205- [key: string]: string206-}207-208-const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({209- papaBear: 'large porridge-pot',210- mamaBear: 'middle-size porridge pot',211- babyBear: 'A little, small, wee pot',212-}))213-214-const meals = [215- 'A tiny, little, wee bowl',216- 'A small, petite, tiny pot',217- 'A wee, itty-bitty, small bowl',218- 'A little, petite, tiny dish',219- 'A tiny, small, wee vessel',220- 'A small, little, wee cauldron',221- 'A little, tiny, small cup',222- 'A wee, small, little jar',223- 'A tiny, wee, small pan',224- 'A small, wee, little crock',225-]226-227-function UpdateBabyBearMeal() {228- useEffect(() => {229- const timer = setInterval(() => {230- useBearFamilyMealsStore.setState({231- babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],232- })233- }, 1000)234-235- return () => {236- clearInterval(timer)237- }238- }, [])239-240- return null241-}242-243-function BearNames() {244- const names = useBearFamilyMealsStore(245- useShallow((state) => Object.keys(state)),246- )247-248- return <div>{names.join(', ')}</div>249-}250-251-export default function App() {252- return (253- <>254- <UpdateBabyBearMeal />255- <BearNames />256- </>257- )258-}259-```260-261-By using `useShallow`, we optimized the rendering process, ensuring that the component only262-re-renders when necessary, which improves overall performance.263-264-## Troubleshooting265-266-TBDdeleted:docs/hooks/use-store-with-equality-fn.md-956 removed
1----2-title: useStoreWithEqualityFn ⚛️3-description: How to use vanilla stores effectively in React4-nav: 295----6-7-`useStoreWithEqualityFn` is a React Hook that lets you use a vanilla store in React, just like8-`useStore`. However, it offers a way to define a custom equality check. This allows for more9-granular control over when components re-render, improving performance and responsiveness.10-11-> [!IMPORTANT]12-> In order to use `useStoreWithEqualityFn` from `zustand/traditional` you need to install13-> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.14-15-```js16-const someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)17-```18-19-- [Types](#types)20- - [Signature](#signature)21-- [Reference](#reference)22-- [Usage](#usage)23- - [Using a global vanilla store in React](#using-a-global-vanilla-store-in-react)24- - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)25- - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)26- - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)27-- [Troubleshooting](#troubleshooting)28-29-### Signature30-31-```ts32-useStoreWithEqualityFn<T, U = T>(store: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U33-```34-35-## Reference36-37-### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`38-39-#### Parameters40-41-- `storeApi`: The instance that lets you access to store API utilities.42-- `selectorFn`: A function that lets you return data that is based on current state.43-- `equalityFn`: A function that lets you skip re-renders.44-45-#### Returns46-47-`useStoreWithEqualityFn` returns any data based on current state depending on the selector function,48-and lets you skip re-renders using an equality function. It should take a store, a selector49-function, and an equality function as arguments.50-51-## Usage52-53-### Using a global vanilla store in React54-55-First, let's set up a store that will hold the position of the dot on the screen. We'll define the56-store to manage `x` and `y` coordinates and provide an action to update these coordinates.57-58-```tsx59-import { createStore, useStore } from 'zustand'60-61-type PositionStoreState = { position: { x: number; y: number } }62-63-type PositionStoreActions = {64- setPosition: (nextPosition: PositionStoreState['position']) => void65-}66-67-type PositionStore = PositionStoreState & PositionStoreActions68-69-const positionStore = createStore<PositionStore>()((set) => ({70- position: { x: 0, y: 0 },71- setPosition: (position) => set({ position }),72-}))73-```74-75-Next, we'll create a `MovingDot` component that renders a div representing the dot. This component76-will use the store to track and update the dot's position.77-78-```tsx79-function MovingDot() {80- const position = useStoreWithEqualityFn(81- positionStore,82- (state) => state.position,83- shallow,84- )85- const setPosition = useStoreWithEqualityFn(86- positionStore,87- (state) => state.setPosition,88- shallow,89- )90-91- return (92- <div93- onPointerMove={(e) => {94- setPosition({95- x: e.clientX,96- y: e.clientY,97- })98- }}99- style={{100- position: 'relative',101- width: '100vw',102- height: '100vh',103- }}104- >105- <div106- style={{107- position: 'absolute',108- backgroundColor: 'red',109- borderRadius: '50%',110- transform: `translate(${position.x}px, ${position.y}px)`,111- left: -10,112- top: -10,113- width: 20,114- height: 20,115- }}116- />117- </div>118- )119-}120-```121-122-Finally, we’ll render the `MovingDot` component in our `App` component.123-124-```tsx125-export default function App() {126- return <MovingDot />127-}128-```129-130-Here is what the code should look like:131-132-```tsx133-import { createStore } from 'zustand'134-import { useStoreWithEqualityFn } from 'zustand/traditional'135-import { shallow } from 'zustand/shallow'136-137-type PositionStoreState = { position: { x: number; y: number } }138-139-type PositionStoreActions = {140- setPosition: (nextPosition: PositionStoreState['position']) => void141-}142-143-type PositionStore = PositionStoreState & PositionStoreActions144-145-const positionStore = createStore<PositionStore>()((set) => ({146- position: { x: 0, y: 0 },147- setPosition: (position) => set({ position }),148-}))149-150-function MovingDot() {151- const position = useStoreWithEqualityFn(152- positionStore,153- (state) => state.position,154- shallow,155- )156- const setPosition = useStoreWithEqualityFn(157- positionStore,158- (state) => state.setPosition,159- shallow,160- )161-162- return (163- <div164- onPointerMove={(e) => {165- setPosition({166- x: e.clientX,167- y: e.clientY,168- })169- }}170- style={{171- position: 'relative',172- width: '100vw',173- height: '100vh',174- }}175- >176- <div177- style={{178- position: 'absolute',179- backgroundColor: 'red',180- borderRadius: '50%',181- transform: `translate(${position.x}px, ${position.y}px)`,182- left: -10,183- top: -10,184- width: 20,185- height: 20,186- }}187- />188- </div>189- )190-}191-192-export default function App() {193- return <MovingDot />194-}195-```196-197-### Using dynamic global vanilla stores in React198-199-First, we'll create a factory function that generates a store for managing the counter state.200-Each tab will have its own instance of this store.201-202-```ts203-import { createStore } from 'zustand'204-205-type CounterState = {206- count: number207-}208-209-type CounterActions = { increment: () => void }210-211-type CounterStore = CounterState & CounterActions212-213-const createCounterStore = () => {214- return createStore<CounterStore>()((set) => ({215- count: 0,216- increment: () => {217- set((state) => ({ count: state.count + 1 }))218- },219- }))220-}221-```222-223-Next, we'll create a factory function that manages the creation and retrieval of counter stores.224-This allows each tab to have its own independent counter.225-226-```ts227-const defaultCounterStores = new Map<228- string,229- ReturnType<typeof createCounterStore>230->()231-232-const createCounterStoreFactory = (233- counterStores: typeof defaultCounterStores,234-) => {235- return (counterStoreKey: string) => {236- if (!counterStores.has(counterStoreKey)) {237- counterStores.set(counterStoreKey, createCounterStore())238- }239- return counterStores.get(counterStoreKey)!240- }241-}242-243-const getOrCreateCounterStoreByKey =244- createCounterStoreFactory(defaultCounterStores)245-```246-247-Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s248-counter.249-250-```tsx251-const [currentTabIndex, setCurrentTabIndex] = useState(0)252-const counterState = useStoreWithEqualityFn(253- getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),254- (state) => state,255- shallow,256-)257-258-return (259- <div style={{ fontFamily: 'monospace' }}>260- <div261- style={{262- display: 'flex',263- gap: '0.5rem',264- borderBottom: '1px solid salmon',265- paddingBottom: 4,266- }}267- >268- <button269- type="button"270- style={{271- border: '1px solid salmon',272- backgroundColor: '#fff',273- cursor: 'pointer',274- }}275- onClick={() => setCurrentTabIndex(0)}276- >277- Tab 1278- </button>279- <button280- type="button"281- style={{282- border: '1px solid salmon',283- backgroundColor: '#fff',284- cursor: 'pointer',285- }}286- onClick={() => setCurrentTabIndex(1)}287- >288- Tab 2289- </button>290- <button291- type="button"292- style={{293- border: '1px solid salmon',294- backgroundColor: '#fff',295- cursor: 'pointer',296- }}297- onClick={() => setCurrentTabIndex(2)}298- >299- Tab 3300- </button>301- </div>302- <div style={{ padding: 4 }}>303- Content of Tab {currentTabIndex + 1}304- <br /> <br />305- <button type="button" onClick={() => counterState.increment()}>306- Count: {counterState.count}307- </button>308- </div>309- </div>310-)311-```312-313-Finally, we'll create the `App` component, which renders the tabs and their respective counters.314-The counter state is managed independently for each tab.315-316-```tsx317-export default function App() {318- return <Tabs />319-}320-```321-322-Here is what the code should look like:323-324-```tsx325-import { useState } from 'react'326-import { createStore } from 'zustand'327-import { useStoreWithEqualityFn } from 'zustand/traditional'328-import { shallow } from 'zustand/shallow'329-330-type CounterState = {331- count: number332-}333-334-type CounterActions = { increment: () => void }335-336-type CounterStore = CounterState & CounterActions337-338-const createCounterStore = () => {339- return createStore<CounterStore>()((set) => ({340- count: 0,341- increment: () => {342- set((state) => ({ count: state.count + 1 }))343- },344- }))345-}346-347-const defaultCounterStores = new Map<348- string,349- ReturnType<typeof createCounterStore>350->()351-352-const createCounterStoreFactory = (353- counterStores: typeof defaultCounterStores,354-) => {355- return (counterStoreKey: string) => {356- if (!counterStores.has(counterStoreKey)) {357- counterStores.set(counterStoreKey, createCounterStore())358- }359- return counterStores.get(counterStoreKey)!360- }361-}362-363-const getOrCreateCounterStoreByKey =364- createCounterStoreFactory(defaultCounterStores)365-366-export default function App() {367- const [currentTabIndex, setCurrentTabIndex] = useState(0)368- const counterState = useStoreWithEqualityFn(369- getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),370- (state) => state,371- shallow,372- )373-374- return (375- <div style={{ fontFamily: 'monospace' }}>376- <div377- style={{378- display: 'flex',379- gap: '0.5rem',380- borderBottom: '1px solid salmon',381- paddingBottom: 4,382- }}383- >384- <button385- type="button"386- style={{387- border: '1px solid salmon',388- backgroundColor: '#fff',389- cursor: 'pointer',390- }}391- onClick={() => setCurrentTabIndex(0)}392- >393- Tab 1394- </button>395- <button396- type="button"397- style={{398- border: '1px solid salmon',399- backgroundColor: '#fff',400- cursor: 'pointer',401- }}402- onClick={() => setCurrentTabIndex(1)}403- >404- Tab 2405- </button>406- <button407- type="button"408- style={{409- border: '1px solid salmon',410- backgroundColor: '#fff',411- cursor: 'pointer',412- }}413- onClick={() => setCurrentTabIndex(2)}414- >415- Tab 3416- </button>417- </div>418- <div style={{ padding: 4 }}>419- Content of Tab {currentTabIndex + 1}420- <br /> <br />421- <button type="button" onClick={() => counterState.increment()}>422- Count: {counterState.count}423- </button>424- </div>425- </div>426- )427-}428-```429-430-### Using scoped (non-global) vanilla store in React431-432-First, let's set up a store that will hold the position of the dot on the screen. We'll define the433-store to manage `x` and `y` coordinates and provide an action to update these coordinates.434-435-```tsx436-type PositionStoreState = { position: { x: number; y: number } }437-438-type PositionStoreActions = {439- setPosition: (nextPosition: PositionStoreState['position']) => void440-}441-442-type PositionStore = PositionStoreState & PositionStoreActions443-444-const createPositionStore = () => {445- return createStore<PositionStore>()((set) => ({446- position: { x: 0, y: 0 },447- setPosition: (position) => set({ position }),448- }))449-}450-```451-452-Next, we'll create a context and a provider component to pass down the store through the React453-component tree. This allows each `MovingDot` component to have its own independent state.454-455-```tsx456-const PositionStoreContext = createContext<ReturnType<457- typeof createPositionStore458-> | null>(null)459-460-function PositionStoreProvider({ children }: { children: ReactNode }) {461- const [store] = useState(() => createPositionStore())462- return (463- <PositionStoreContext.Provider value={store}>464- {children}465- </PositionStoreContext.Provider>466- )467-}468-```469-470-To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook471-will read the store from the context and allow us to select specific parts of the state.472-473-```ts474-function usePositionStore<U>(selector: (state: PositionStore) => U) {475- const store = useContext(PositionStoreContext)476-477- if (store === null) {478- throw new Error(479- 'usePositionStore must be used within PositionStoreProvider',480- )481- }482-483- return useStoreWithEqualityFn(store, selector, shallow)484-}485-```486-487-Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor488-within its container.489-490-```tsx491-function MovingDot({ color }: { color: string }) {492- const position = usePositionStore((state) => state.position)493- const setPosition = usePositionStore((state) => state.setPosition)494-495- return (496- <div497- onPointerMove={(e) => {498- setPosition({499- x:500- e.clientX > e.currentTarget.clientWidth501- ? e.clientX - e.currentTarget.clientWidth502- : e.clientX,503- y: e.clientY,504- })505- }}506- style={{507- position: 'relative',508- width: '50vw',509- height: '100vh',510- }}511- >512- <div513- style={{514- position: 'absolute',515- backgroundColor: color,516- borderRadius: '50%',517- transform: `translate(${position.x}px, ${position.y}px)`,518- left: -10,519- top: -10,520- width: 20,521- height: 20,522- }}523- />524- </div>525- )526-}527-```528-529-Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`530-components, each with its own independent state.531-532-```tsx533-export default function App() {534- return (535- <div style={{ display: 'flex' }}>536- <PositionStoreProvider>537- <MovingDot color="red" />538- </PositionStoreProvider>539- <PositionStoreProvider>540- <MovingDot color="blue" />541- </PositionStoreProvider>542- </div>543- )544-}545-```546-547-Here is what the code should look like:548-549-```tsx550-import { type ReactNode, useState, createContext, useContext } from 'react'551-import { createStore } from 'zustand'552-import { useStoreWithEqualityFn } from 'zustand/traditional'553-import { shallow } from 'zustand/shallow'554-555-type PositionStoreState = { position: { x: number; y: number } }556-557-type PositionStoreActions = {558- setPosition: (nextPosition: PositionStoreState['position']) => void559-}560-561-type PositionStore = PositionStoreState & PositionStoreActions562-563-const createPositionStore = () => {564- return createStore<PositionStore>()((set) => ({565- position: { x: 0, y: 0 },566- setPosition: (position) => set({ position }),567- }))568-}569-570-const PositionStoreContext = createContext<ReturnType<571- typeof createPositionStore572-> | null>(null)573-574-function PositionStoreProvider({ children }: { children: ReactNode }) {575- const [store] = useState(() => createPositionStore())576- return (577- <PositionStoreContext.Provider value={store}>578- {children}579- </PositionStoreContext.Provider>580- )581-}582-583-function usePositionStore<U>(selector: (state: PositionStore) => U) {584- const store = useContext(PositionStoreContext)585-586- if (store === null) {587- throw new Error(588- 'usePositionStore must be used within PositionStoreProvider',589- )590- }591-592- return useStoreWithEqualityFn(store, selector, shallow)593-}594-595-function MovingDot({ color }: { color: string }) {596- const position = usePositionStore((state) => state.position)597- const setPosition = usePositionStore((state) => state.setPosition)598-599- return (600- <div601- onPointerMove={(e) => {602- setPosition({603- x:604- e.clientX > e.currentTarget.clientWidth605- ? e.clientX - e.currentTarget.clientWidth606- : e.clientX,607- y: e.clientY,608- })609- }}610- style={{611- position: 'relative',612- width: '50vw',613- height: '100vh',614- }}615- >616- <div617- style={{618- position: 'absolute',619- backgroundColor: color,620- borderRadius: '50%',621- transform: `translate(${position.x}px, ${position.y}px)`,622- left: -10,623- top: -10,624- width: 20,625- height: 20,626- }}627- />628- </div>629- )630-}631-632-export default function App() {633- return (634- <div style={{ display: 'flex' }}>635- <PositionStoreProvider>636- <MovingDot color="red" />637- </PositionStoreProvider>638- <PositionStoreProvider>639- <MovingDot color="blue" />640- </PositionStoreProvider>641- </div>642- )643-}644-```645-646-### Using dynamic scoped (non-global) vanilla stores in React647-648-First, we'll create a factory function that generates a store for managing the counter state.649-Each tab will have its own instance of this store.650-651-```ts652-type CounterState = {653- count: number654-}655-656-type CounterActions = { increment: () => void }657-658-type CounterStore = CounterState & CounterActions659-660-const createCounterStore = () => {661- return createStore<CounterStore>()((set) => ({662- count: 0,663- increment: () => {664- set((state) => ({ count: state.count + 1 }))665- },666- }))667-}668-```669-670-Next, we'll create a factory function that manages the creation and retrieval of counter stores.671-This allows each tab to have its own independent counter.672-673-```ts674-const createCounterStoreFactory = (675- counterStores: Map<string, ReturnType<typeof createCounterStore>>,676-) => {677- return (counterStoreKey: string) => {678- if (!counterStores.has(counterStoreKey)) {679- counterStores.set(counterStoreKey, createCounterStore())680- }681- return counterStores.get(counterStoreKey)!682- }683-}684-```685-686-Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context687-for this.688-689-```tsx690-const CounterStoresContext = createContext(null)691-692-const CounterStoresProvider = ({ children }) => {693- const [stores] = useState(694- () => new Map<string, ReturnType<typeof createCounterStore>>(),695- )696-697- return (698- <CounterStoresContext.Provider value={stores}>699- {children}700- </CounterStoresContext.Provider>701- )702-}703-```704-705-Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a706-given tab.707-708-```tsx709-const useCounterStore = <U,>(710- key: string,711- selector: (state: CounterStore) => U,712-) => {713- const stores = useContext(CounterStoresContext)714-715- if (stores === undefined) {716- throw new Error('useCounterStore must be used within CounterStoresProvider')717- }718-719- const getOrCreateCounterStoreByKey = useCallback(720- (key: string) => createCounterStoreFactory(stores!)(key),721- [stores],722- )723-724- return useStore(getOrCreateCounterStoreByKey(key), selector)725-}726-```727-728-Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s729-counter.730-731-```tsx732-function Tabs() {733- const [currentTabIndex, setCurrentTabIndex] = useState(0)734- const counterState = useCounterStore(735- `tab-${currentTabIndex}`,736- (state) => state,737- )738-739- return (740- <div style={{ fontFamily: 'monospace' }}>741- <div742- style={{743- display: 'flex',744- gap: '0.5rem',745- borderBottom: '1px solid salmon',746- paddingBottom: 4,747- }}748- >749- <button750- type="button"751- style={{752- border: '1px solid salmon',753- backgroundColor: '#fff',754- cursor: 'pointer',755- }}756- onClick={() => setCurrentTabIndex(0)}757- >758- Tab 1759- </button>760- <button761- type="button"762- style={{763- border: '1px solid salmon',764- backgroundColor: '#fff',765- cursor: 'pointer',766- }}767- onClick={() => setCurrentTabIndex(1)}768- >769- Tab 2770- </button>771- <button772- type="button"773- style={{774- border: '1px solid salmon',775- backgroundColor: '#fff',776- cursor: 'pointer',777- }}778- onClick={() => setCurrentTabIndex(2)}779- >780- Tab 3781- </button>782- </div>783- <div style={{ padding: 4 }}>784- Content of Tab {currentTabIndex + 1}785- <br /> <br />786- <button type="button" onClick={() => counterState.increment()}>787- Count: {counterState.count}788- </button>789- </div>790- </div>791- )792-}793-```794-795-Finally, we'll create the `App` component, which renders the tabs and their respective counters.796-The counter state is managed independently for each tab.797-798-```tsx799-export default function App() {800- return (801- <CounterStoresProvider>802- <Tabs />803- </CounterStoresProvider>804- )805-}806-```807-808-Here is what the code should look like:809-810-```tsx811-import {812- type ReactNode,813- useState,814- useCallback,815- useContext,816- createContext,817-} from 'react'818-import { createStore, useStore } from 'zustand'819-820-type CounterState = {821- count: number822-}823-824-type CounterActions = { increment: () => void }825-826-type CounterStore = CounterState & CounterActions827-828-const createCounterStore = () => {829- return createStore<CounterStore>()((set) => ({830- count: 0,831- increment: () => {832- set((state) => ({ count: state.count + 1 }))833- },834- }))835-}836-837-const createCounterStoreFactory = (838- counterStores: Map<string, ReturnType<typeof createCounterStore>>,839-) => {840- return (counterStoreKey: string) => {841- if (!counterStores.has(counterStoreKey)) {842- counterStores.set(counterStoreKey, createCounterStore())843- }844- return counterStores.get(counterStoreKey)!845- }846-}847-848-const CounterStoresContext = createContext<Map<849- string,850- ReturnType<typeof createCounterStore>851-> | null>(null)852-853-const CounterStoresProvider = ({ children }: { children: ReactNode }) => {854- const [stores] = useState(855- () => new Map<string, ReturnType<typeof createCounterStore>>(),856- )857-858- return (859- <CounterStoresContext.Provider value={stores}>860- {children}861- </CounterStoresContext.Provider>862- )863-}864-865-const useCounterStore = <U,>(866- key: string,867- selector: (state: CounterStore) => U,868-) => {869- const stores = useContext(CounterStoresContext)870-871- if (stores === undefined) {872- throw new Error('useCounterStore must be used within CounterStoresProvider')873- }874-875- const getOrCreateCounterStoreByKey = useCallback(876- (key: string) => createCounterStoreFactory(stores!)(key),877- [stores],878- )879-880- return useStore(getOrCreateCounterStoreByKey(key), selector)881-}882-883-function Tabs() {884- const [currentTabIndex, setCurrentTabIndex] = useState(0)885- const counterState = useCounterStore(886- `tab-${currentTabIndex}`,887- (state) => state,888- )889-890- return (891- <div style={{ fontFamily: 'monospace' }}>892- <div893- style={{894- display: 'flex',895- gap: '0.5rem',896- borderBottom: '1px solid salmon',897- paddingBottom: 4,898- }}899- >900- <button901- type="button"902- style={{903- border: '1px solid salmon',904- backgroundColor: '#fff',905- cursor: 'pointer',906- }}907- onClick={() => setCurrentTabIndex(0)}908- >909- Tab 1910- </button>911- <button912- type="button"913- style={{914- border: '1px solid salmon',915- backgroundColor: '#fff',916- cursor: 'pointer',917- }}918- onClick={() => setCurrentTabIndex(1)}919- >920- Tab 2921- </button>922- <button923- type="button"924- style={{925- border: '1px solid salmon',926- backgroundColor: '#fff',927- cursor: 'pointer',928- }}929- onClick={() => setCurrentTabIndex(2)}930- >931- Tab 3932- </button>933- </div>934- <div style={{ padding: 4 }}>935- Content of Tab {currentTabIndex + 1}936- <br /> <br />937- <button type="button" onClick={() => counterState.increment()}>938- Count: {counterState.count}939- </button>940- </div>941- </div>942- )943-}944-945-export default function App() {946- return (947- <CounterStoresProvider>948- <Tabs />949- </CounterStoresProvider>950- )951-}952-```953-954-## Troubleshooting955-956-TBDdeleted:docs/hooks/use-store.md-922 removed
1----2-title: useStore ⚛️3-description: How to use vanilla stores in React4-nav: 305----6-7-`useStore` is a React Hook that lets you use a vanilla store in React.8-9-```js10-const someState = useStore(store, selectorFn)11-```12-13-- [Types](#types)14- - [Signature](#signature)15-- [Reference](#reference)16-- [Usage](#usage)17- - [Use a vanilla store in React](#use-a-vanilla-store-in-react)18- - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)19- - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)20- - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)21-- [Troubleshooting](#troubleshooting)22-23-## Types24-25-### Signature26-27-```ts28-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.39-40-#### Returns41-42-`useStore` returns any data based on current state depending on the selector function. It should43-take a store, and a selector function as arguments.44-45-## Usage46-47-### Using a global vanilla store in React48-49-First, let's set up a store that will hold the position of the dot on the screen. We'll define the50-store to manage `x` and `y` coordinates and provide an action to update these coordinates.51-52-```tsx53-type PositionStoreState = { position: { x: number; y: number } }54-55-type PositionStoreActions = {56- setPosition: (nextPosition: PositionStoreState['position']) => void57-}58-59-type PositionStore = PositionStoreState & PositionStoreActions60-61-const positionStore = createStore<PositionStore>()((set) => ({62- position: { x: 0, y: 0 },63- setPosition: (position) => set({ position }),64-}))65-```66-67-Next, we'll create a `MovingDot` component that renders a div representing the dot. This component68-will use the store to track and update the dot's position.69-70-```tsx71-function MovingDot() {72- const position = useStore(positionStore, (state) => state.position)73- const setPosition = useStore(positionStore, (state) => state.setPosition)74-75- return (76- <div77- onPointerMove={(e) => {78- setPosition({79- x: e.clientX,80- y: e.clientY,81- })82- }}83- style={{84- position: 'relative',85- width: '100vw',86- height: '100vh',87- }}88- >89- <div90- style={{91- position: 'absolute',92- backgroundColor: 'red',93- borderRadius: '50%',94- transform: `translate(${position.x}px, ${position.y}px)`,95- left: -10,96- top: -10,97- width: 20,98- height: 20,99- }}100- />101- </div>102- )103-}104-```105-106-Finally, we’ll render the `MovingDot` component in our `App` component.107-108-```tsx109-export default function App() {110- return <MovingDot />111-}112-```113-114-Here is what the code should look like:115-116-```tsx117-import { createStore, useStore } from 'zustand'118-119-type PositionStoreState = { position: { x: number; y: number } }120-121-type PositionStoreActions = {122- setPosition: (nextPosition: PositionStoreState['position']) => void123-}124-125-type PositionStore = PositionStoreState & PositionStoreActions126-127-const positionStore = createStore<PositionStore>()((set) => ({128- position: { x: 0, y: 0 },129- setPosition: (position) => set({ position }),130-}))131-132-function MovingDot() {133- const position = useStore(positionStore, (state) => state.position)134- const setPosition = useStore(positionStore, (state) => state.setPosition)135-136- return (137- <div138- onPointerMove={(e) => {139- setPosition({140- x: e.clientX,141- y: e.clientY,142- })143- }}144- style={{145- position: 'relative',146- width: '100vw',147- height: '100vh',148- }}149- >150- <div151- style={{152- position: 'absolute',153- backgroundColor: 'red',154- borderRadius: '50%',155- transform: `translate(${position.x}px, ${position.y}px)`,156- left: -10,157- top: -10,158- width: 20,159- height: 20,160- }}161- />162- </div>163- )164-}165-166-export default function App() {167- return <MovingDot />168-}169-```170-171-### Using dynamic global vanilla stores in React172-173-First, we'll create a factory function that generates a store for managing the counter state.174-Each tab will have its own instance of this store.175-176-```ts177-type CounterState = {178- count: number179-}180-181-type CounterActions = { increment: () => void }182-183-type CounterStore = CounterState & CounterActions184-185-const createCounterStore = () => {186- return createStore<CounterStore>()((set) => ({187- count: 0,188- increment: () => {189- set((state) => ({ count: state.count + 1 }))190- },191- }))192-}193-```194-195-Next, we'll create a factory function that manages the creation and retrieval of counter stores.196-This allows each tab to have its own independent counter.197-198-```ts199-const defaultCounterStores = new Map<200- string,201- ReturnType<typeof createCounterStore>202->()203-204-const createCounterStoreFactory = (205- counterStores: typeof defaultCounterStores,206-) => {207- return (counterStoreKey: string) => {208- if (!counterStores.has(counterStoreKey)) {209- counterStores.set(counterStoreKey, createCounterStore())210- }211- return counterStores.get(counterStoreKey)!212- }213-}214-215-const getOrCreateCounterStoreByKey =216- createCounterStoreFactory(defaultCounterStores)217-```218-219-Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s220-counter.221-222-```tsx223-const [currentTabIndex, setCurrentTabIndex] = useState(0)224-const counterState = useStore(225- getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),226-)227-228-return (229- <div style={{ fontFamily: 'monospace' }}>230- <div231- style={{232- display: 'flex',233- gap: '0.5rem',234- borderBottom: '1px solid salmon',235- paddingBottom: 4,236- }}237- >238- <button239- type="button"240- style={{241- border: '1px solid salmon',242- backgroundColor: '#fff',243- cursor: 'pointer',244- }}245- onClick={() => setCurrentTabIndex(0)}246- >247- Tab 1248- </button>249- <button250- type="button"251- style={{252- border: '1px solid salmon',253- backgroundColor: '#fff',254- cursor: 'pointer',255- }}256- onClick={() => setCurrentTabIndex(1)}257- >258- Tab 2259- </button>260- <button261- type="button"262- style={{263- border: '1px solid salmon',264- backgroundColor: '#fff',265- cursor: 'pointer',266- }}267- onClick={() => setCurrentTabIndex(2)}268- >269- Tab 3270- </button>271- </div>272- <div style={{ padding: 4 }}>273- Content of Tab {currentTabIndex + 1}274- <br /> <br />275- <button type="button" onClick={() => counterState.increment()}>276- Count: {counterState.count}277- </button>278- </div>279- </div>280-)281-```282-283-Finally, we'll create the `App` component, which renders the tabs and their respective counters.284-The counter state is managed independently for each tab.285-286-```tsx287-export default function App() {288- return <Tabs />289-}290-```291-292-Here is what the code should look like:293-294-```tsx295-import { useState } from 'react'296-import { createStore, useStore } from 'zustand'297-298-type CounterState = {299- count: number300-}301-302-type CounterActions = { increment: () => void }303-304-type CounterStore = CounterState & CounterActions305-306-const createCounterStore = () => {307- return createStore<CounterStore>()((set) => ({308- count: 0,309- increment: () => {310- set((state) => ({ count: state.count + 1 }))311- },312- }))313-}314-315-const defaultCounterStores = new Map<316- string,317- ReturnType<typeof createCounterStore>318->()319-320-const createCounterStoreFactory = (321- counterStores: typeof defaultCounterStores,322-) => {323- return (counterStoreKey: string) => {324- if (!counterStores.has(counterStoreKey)) {325- counterStores.set(counterStoreKey, createCounterStore())326- }327- return counterStores.get(counterStoreKey)!328- }329-}330-331-const getOrCreateCounterStoreByKey =332- createCounterStoreFactory(defaultCounterStores)333-334-export default function App() {335- const [currentTabIndex, setCurrentTabIndex] = useState(0)336- const counterState = useStore(337- getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),338- )339-340- return (341- <div style={{ fontFamily: 'monospace' }}>342- <div343- style={{344- display: 'flex',345- gap: '0.5rem',346- borderBottom: '1px solid salmon',347- paddingBottom: 4,348- }}349- >350- <button351- type="button"352- style={{353- border: '1px solid salmon',354- backgroundColor: '#fff',355- cursor: 'pointer',356- }}357- onClick={() => setCurrentTabIndex(0)}358- >359- Tab 1360- </button>361- <button362- type="button"363- style={{364- border: '1px solid salmon',365- backgroundColor: '#fff',366- cursor: 'pointer',367- }}368- onClick={() => setCurrentTabIndex(1)}369- >370- Tab 2371- </button>372- <button373- type="button"374- style={{375- border: '1px solid salmon',376- backgroundColor: '#fff',377- cursor: 'pointer',378- }}379- onClick={() => setCurrentTabIndex(2)}380- >381- Tab 3382- </button>383- </div>384- <div style={{ padding: 4 }}>385- Content of Tab {currentTabIndex + 1}386- <br /> <br />387- <button type="button" onClick={() => counterState.increment()}>388- Count: {counterState.count}389- </button>390- </div>391- </div>392- )393-}394-```395-396-### Using scoped (non-global) vanilla store in React397-398-First, let's set up a store that will hold the position of the dot on the screen. We'll define the399-store to manage `x` and `y` coordinates and provide an action to update these coordinates.400-401-```tsx402-type PositionStoreState = { position: { x: number; y: number } }403-404-type PositionStoreActions = {405- setPosition: (nextPosition: PositionStoreState['position']) => void406-}407-408-type PositionStore = PositionStoreState & PositionStoreActions409-410-const createPositionStore = () => {411- return createStore<PositionStore>()((set) => ({412- position: { x: 0, y: 0 },413- setPosition: (position) => set({ position }),414- }))415-}416-```417-418-Next, we'll create a context and a provider component to pass down the store through the React419-component tree. This allows each `MovingDot` component to have its own independent state.420-421-```tsx422-const PositionStoreContext = createContext<ReturnType<423- typeof createPositionStore424-> | null>(null)425-426-function PositionStoreProvider({ children }: { children: ReactNode }) {427- const [store] = useState(() => createPositionStore())428- return (429- <PositionStoreContext.Provider value={store}>430- {children}431- </PositionStoreContext.Provider>432- )433-}434-```435-436-To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook437-will read the store from the context and allow us to select specific parts of the state.438-439-```ts440-function usePositionStore<U>(selector: (state: PositionStore) => U) {441- const store = useContext(PositionStoreContext)442-443- if (store === null) {444- throw new Error(445- 'usePositionStore must be used within PositionStoreProvider',446- )447- }448-449- return useStore(store, selector)450-}451-```452-453-Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor454-within its container.455-456-```tsx457-function MovingDot({ color }: { color: string }) {458- const position = usePositionStore((state) => state.position)459- const setPosition = usePositionStore((state) => state.setPosition)460-461- return (462- <div463- onPointerMove={(e) => {464- setPosition({465- x:466- e.clientX > e.currentTarget.clientWidth467- ? e.clientX - e.currentTarget.clientWidth468- : e.clientX,469- y: e.clientY,470- })471- }}472- style={{473- position: 'relative',474- width: '50vw',475- height: '100vh',476- }}477- >478- <div479- style={{480- position: 'absolute',481- backgroundColor: color,482- borderRadius: '50%',483- transform: `translate(${position.x}px, ${position.y}px)`,484- left: -10,485- top: -10,486- width: 20,487- height: 20,488- }}489- />490- </div>491- )492-}493-```494-495-Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`496-components, each with its own independent state.497-498-```tsx499-export default function App() {500- return (501- <div style={{ display: 'flex' }}>502- <PositionStoreProvider>503- <MovingDot color="red" />504- </PositionStoreProvider>505- <PositionStoreProvider>506- <MovingDot color="blue" />507- </PositionStoreProvider>508- </div>509- )510-}511-```512-513-Here is what the code should look like:514-515-```tsx516-import { type ReactNode, useState, createContext, useContext } from 'react'517-import { createStore, useStore } from 'zustand'518-519-type PositionStoreState = { position: { x: number; y: number } }520-521-type PositionStoreActions = {522- setPosition: (nextPosition: PositionStoreState['position']) => void523-}524-525-type PositionStore = PositionStoreState & PositionStoreActions526-527-const createPositionStore = () => {528- return createStore<PositionStore>()((set) => ({529- position: { x: 0, y: 0 },530- setPosition: (position) => set({ position }),531- }))532-}533-534-const PositionStoreContext = createContext<ReturnType<535- typeof createPositionStore536-> | null>(null)537-538-function PositionStoreProvider({ children }: { children: ReactNode }) {539- const [store] = useState(() => createPositionStore())540- return (541- <PositionStoreContext.Provider value={store}>542- {children}543- </PositionStoreContext.Provider>544- )545-}546-547-function usePositionStore<U>(selector: (state: PositionStore) => U) {548- const store = useContext(PositionStoreContext)549-550- if (store === null) {551- throw new Error(552- 'usePositionStore must be used within PositionStoreProvider',553- )554- }555-556- return useStore(store, selector)557-}558-559-function MovingDot({ color }: { color: string }) {560- const position = usePositionStore((state) => state.position)561- const setPosition = usePositionStore((state) => state.setPosition)562-563- return (564- <div565- onPointerMove={(e) => {566- setPosition({567- x:568- e.clientX > e.currentTarget.clientWidth569- ? e.clientX - e.currentTarget.clientWidth570- : e.clientX,571- y: e.clientY,572- })573- }}574- style={{575- position: 'relative',576- width: '50vw',577- height: '100vh',578- }}579- >580- <div581- style={{582- position: 'absolute',583- backgroundColor: color,584- borderRadius: '50%',585- transform: `translate(${position.x}px, ${position.y}px)`,586- left: -10,587- top: -10,588- width: 20,589- height: 20,590- }}591- />592- </div>593- )594-}595-596-export default function App() {597- return (598- <div style={{ display: 'flex' }}>599- <PositionStoreProvider>600- <MovingDot color="red" />601- </PositionStoreProvider>602- <PositionStoreProvider>603- <MovingDot color="blue" />604- </PositionStoreProvider>605- </div>606- )607-}608-```609-610-### Using dynamic scoped (non-global) vanilla stores in React611-612-First, we'll create a factory function that generates a store for managing the counter state.613-Each tab will have its own instance of this store.614-615-```ts616-import { createStore } from 'zustand'617-618-type CounterState = {619- count: number620-}621-622-type CounterActions = { increment: () => void }623-624-type CounterStore = CounterState & CounterActions625-626-const createCounterStore = () => {627- return createStore<CounterStore>()((set) => ({628- count: 0,629- increment: () => {630- set((state) => ({ count: state.count + 1 }))631- },632- }))633-}634-```635-636-Next, we'll create a factory function that manages the creation and retrieval of counter stores.637-This allows each tab to have its own independent counter.638-639-```ts640-const createCounterStoreFactory = (641- counterStores: Map<string, ReturnType<typeof createCounterStore>>,642-) => {643- return (counterStoreKey: string) => {644- if (!counterStores.has(counterStoreKey)) {645- counterStores.set(counterStoreKey, createCounterStore())646- }647- return counterStores.get(counterStoreKey)!648- }649-}650-```651-652-Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context653-for this.654-655-```tsx656-const CounterStoresContext = createContext(null)657-658-const CounterStoresProvider = ({ children }) => {659- const [stores] = useState(660- () => new Map<string, ReturnType<typeof createCounterStore>>(),661- )662-663- return (664- <CounterStoresContext.Provider value={stores}>665- {children}666- </CounterStoresContext.Provider>667- )668-}669-```670-671-Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a672-given tab.673-674-```tsx675-const useCounterStore = <U>(676- currentTabIndex: number,677- selector: (state: CounterStore) => U,678-) => {679- const stores = useContext(CounterStoresContext)680-681- if (stores === undefined) {682- throw new Error('useCounterStore must be used within CounterStoresProvider')683- }684-685- const getOrCreateCounterStoreByKey = useCallback(686- () => createCounterStoreFactory(stores),687- [stores],688- )689-690- return useStore(getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`))691-}692-```693-694-Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s695-counter.696-697-```tsx698-function Tabs() {699- const [currentTabIndex, setCurrentTabIndex] = useState(0)700- const counterState = useCounterStore(701- `tab-${currentTabIndex}`,702- (state) => state,703- )704-705- return (706- <div style={{ fontFamily: 'monospace' }}>707- <div708- style={{709- display: 'flex',710- gap: '0.5rem',711- borderBottom: '1px solid salmon',712- paddingBottom: 4,713- }}714- >715- <button716- type="button"717- style={{718- border: '1px solid salmon',719- backgroundColor: '#fff',720- cursor: 'pointer',721- }}722- onClick={() => setCurrentTabIndex(0)}723- >724- Tab 1725- </button>726- <button727- type="button"728- style={{729- border: '1px solid salmon',730- backgroundColor: '#fff',731- cursor: 'pointer',732- }}733- onClick={() => setCurrentTabIndex(1)}734- >735- Tab 2736- </button>737- <button738- type="button"739- style={{740- border: '1px solid salmon',741- backgroundColor: '#fff',742- cursor: 'pointer',743- }}744- onClick={() => setCurrentTabIndex(2)}745- >746- Tab 3747- </button>748- </div>749- <div style={{ padding: 4 }}>750- Content of Tab {currentTabIndex + 1}751- <br /> <br />752- <button type="button" onClick={() => counterState.increment()}>753- Count: {counterState.count}754- </button>755- </div>756- </div>757- )758-}759-```760-761-Finally, we'll create the `App` component, which renders the tabs and their respective counters.762-The counter state is managed independently for each tab.763-764-```tsx765-export default function App() {766- return (767- <CounterStoresProvider>768- <Tabs />769- </CounterStoresProvider>770- )771-}772-```773-774-Here is what the code should look like:775-776-```tsx777-import {778- type ReactNode,779- useState,780- useCallback,781- useContext,782- createContext,783-} from 'react'784-import { createStore, useStore } from 'zustand'785-786-type CounterState = {787- count: number788-}789-790-type CounterActions = { increment: () => void }791-792-type CounterStore = CounterState & CounterActions793-794-const createCounterStore = () => {795- return createStore<CounterStore>()((set) => ({796- count: 0,797- increment: () => {798- set((state) => ({ count: state.count + 1 }))799- },800- }))801-}802-803-const createCounterStoreFactory = (804- counterStores: Map<string, ReturnType<typeof createCounterStore>>,805-) => {806- return (counterStoreKey: string) => {807- if (!counterStores.has(counterStoreKey)) {808- counterStores.set(counterStoreKey, createCounterStore())809- }810- return counterStores.get(counterStoreKey)!811- }812-}813-814-const CounterStoresContext = createContext<Map<815- string,816- ReturnType<typeof createCounterStore>817-> | null>(null)818-819-const CounterStoresProvider = ({ children }: { children: ReactNode }) => {820- const [stores] = useState(821- () => new Map<string, ReturnType<typeof createCounterStore>>(),822- )823-824- return (825- <CounterStoresContext.Provider value={stores}>826- {children}827- </CounterStoresContext.Provider>828- )829-}830-831-const useCounterStore = <U,>(832- key: string,833- selector: (state: CounterStore) => U,834-) => {835- const stores = useContext(CounterStoresContext)836-837- if (stores === undefined) {838- throw new Error('useCounterStore must be used within CounterStoresProvider')839- }840-841- const getOrCreateCounterStoreByKey = useCallback(842- (key: string) => createCounterStoreFactory(stores!)(key),843- [stores],844- )845-846- return useStore(getOrCreateCounterStoreByKey(key), selector)847-}848-849-function Tabs() {850- const [currentTabIndex, setCurrentTabIndex] = useState(0)851- const counterState = useCounterStore(852- `tab-${currentTabIndex}`,853- (state) => state,854- )855-856- return (857- <div style={{ fontFamily: 'monospace' }}>858- <div859- style={{860- display: 'flex',861- gap: '0.5rem',862- borderBottom: '1px solid salmon',863- paddingBottom: 4,864- }}865- >866- <button867- type="button"868- style={{869- border: '1px solid salmon',870- backgroundColor: '#fff',871- cursor: 'pointer',872- }}873- onClick={() => setCurrentTabIndex(0)}874- >875- Tab 1876- </button>877- <button878- type="button"879- style={{880- border: '1px solid salmon',881- backgroundColor: '#fff',882- cursor: 'pointer',883- }}884- onClick={() => setCurrentTabIndex(1)}885- >886- Tab 2887- </button>888- <button889- type="button"890- style={{891- border: '1px solid salmon',892- backgroundColor: '#fff',893- cursor: 'pointer',894- }}895- onClick={() => setCurrentTabIndex(2)}896- >897- Tab 3898- </button>899- </div>900- <div style={{ padding: 4 }}>901- Content of Tab {currentTabIndex + 1}902- <br /> <br />903- <button type="button" onClick={() => counterState.increment()}>904- Count: {counterState.count}905- </button>906- </div>907- </div>908- )909-}910-911-export default function App() {912- return (913- <CounterStoresProvider>914- <Tabs />915- </CounterStoresProvider>916- )917-}918-```919-920-## Troubleshooting921-922-TBDdeleted:docs/integrations/immer-middleware.md-129 removed
1----2-title: Immer middleware3-nav: 184----5-6-The [Immer](https://github.com/immerjs/immer) middleware enables you7-to use immutable state in a more convenient way.8-Also, with Immer, you can simplify handling9-immutable data structures in Zustand.10-11-## Installation12-13-In order to use the Immer middleware in Zustand,14-you will need to install Immer as a direct dependency.15-16-```bash17-npm install immer18-```19-20-## Usage21-22-(Notice the extra parentheses after the type parameter as mentioned in the [Advanced Typescript Guide](../guides/advanced-typescript.md)).23-24-Updating simple states25-26-```ts27-import { create } from 'zustand'28-import { immer } from 'zustand/middleware/immer'29-30-type State = {31- count: number32-}33-34-type Actions = {35- increment: (qty: number) => void36- decrement: (qty: number) => void37-}38-39-export const useCountStore = create<State & Actions>()(40- immer((set) => ({41- count: 0,42- increment: (qty: number) =>43- set((state) => {44- state.count += qty45- }),46- decrement: (qty: number) =>47- set((state) => {48- state.count -= qty49- }),50- })),51-)52-```53-54-Updating complex states55-56-```ts57-import { create } from 'zustand'58-import { immer } from 'zustand/middleware/immer'59-60-interface Todo {61- id: string62- title: string63- done: boolean64-}65-66-type State = {67- todos: Record<string, Todo>68-}69-70-type Actions = {71- toggleTodo: (todoId: string) => void72-}73-74-export const useTodoStore = create<State & Actions>()(75- immer((set) => ({76- todos: {77- '82471c5f-4207-4b1d-abcb-b98547e01a3e': {78- id: '82471c5f-4207-4b1d-abcb-b98547e01a3e',79- title: 'Learn Zustand',80- done: false,81- },82- '354ee16c-bfdd-44d3-afa9-e93679bda367': {83- id: '354ee16c-bfdd-44d3-afa9-e93679bda367',84- title: 'Learn Jotai',85- done: false,86- },87- '771c85c5-46ea-4a11-8fed-36cc2c7be344': {88- id: '771c85c5-46ea-4a11-8fed-36cc2c7be344',89- title: 'Learn Valtio',90- done: false,91- },92- '363a4bac-083f-47f7-a0a2-aeeee153a99c': {93- id: '363a4bac-083f-47f7-a0a2-aeeee153a99c',94- title: 'Learn Signals',95- done: false,96- },97- },98- toggleTodo: (todoId: string) =>99- set((state) => {100- state.todos[todoId].done = !state.todos[todoId].done101- }),102- })),103-)104-```105-106-## Gotchas107-108-In this section you will find some things109-that you need to keep in mind when using Zustand with Immer.110-111-### My subscriptions aren't being called112-113-If you are using Immer,114-make sure you are actually following115-[the rules of Immer](https://immerjs.github.io/immer/pitfalls).116-117-For example, you have to add `[immerable] = true` for118-[class objects](https://immerjs.github.io/immer/complex-objects) to work.119-If you don't do this, Immer will still mutate the object,120-but not as a proxy, so it will also update the current state.121-Zustand checks if the state has actually changed,122-so since both the current state and the next state are123-equal (if you don't do it correctly),124-Zustand will skip calling the subscriptions.125-126-## Demos127-128-- Basic: https://stackblitz.com/edit/vitejs-vite-3sgc4ejy129-- Advanced: https://stackblitz.com/edit/vitejs-vite-jxxtuyj3deleted:docs/integrations/persisting-store-data.md-834 removed
1----2-title: Persisting store data3-nav: 204----5-6-The Persist middleware enables you to store7-your Zustand state in a storage8-(e.g., `localStorage`, `AsyncStorage`, `IndexedDB`, etc.),9-thus persisting its data.10-11-Note that this middleware supports both12-synchronous storages, like `localStorage`,13-and asynchronous storages, like `AsyncStorage`,14-but using an asynchronous storage does come with a cost.15-See [Hydration and asynchronous storages](#hydration-and-asynchronous-storages)16-for more details.17-18-## Simple example19-20-```ts21-import { create } from 'zustand'22-import { persist, createJSONStorage } from 'zustand/middleware'23-24-export const useBearStore = create()(25- persist(26- (set, get) => ({27- bears: 0,28- addABear: () => set({ bears: get().bears + 1 }),29- }),30- {31- name: 'food-storage', // name of the item in the storage (must be unique)32- storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used33- },34- ),35-)36-```37-38-## Typescript simple example39-40-```ts41-import { create } from 'zustand'42-import { persist, createJSONStorage } from 'zustand/middleware'43-44-type BearStore = {45- bears: number46- addABear: () => void47-}48-49-export const useBearStore = create<BearStore>()(50- persist(51- (set, get) => ({52- bears: 0,53- addABear: () => set({ bears: get().bears + 1 }),54- }),55- {56- name: 'food-storage', // name of the item in the storage (must be unique)57- storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used58- },59- ),60-)61-```62-63-## Options64-65-### `name`66-67-This is the only required option.68-The given name is going to be the key69-used to store your Zustand state in the storage,70-so it must be unique.71-72-### `storage`73-74-> Type: `() => StateStorage`75-76-The `StateStorage` can be imported with:77-78-```ts79-import { StateStorage } from 'zustand/middleware'80-```81-82-> Default: `createJSONStorage(() => localStorage)`83-84-Enables you to use your own storage. Simply pass a function that returns the storage you want to use. It's recommended to use the [`createJSONStorage`](#createjsonstorage) helper function to create a `storage` object that is compliant with the `StateStorage` interface.85-86-Example:87-88-```ts89-import { persist, createJSONStorage } from 'zustand/middleware'90-91-export const useBoundStore = create(92- persist(93- (set, get) => ({94- // ...95- }),96- {97- // ...98- storage: createJSONStorage(() => AsyncStorage),99- },100- ),101-)102-```103-104-### `partialize`105-106-> Type: `(state: Object) => Object`107-108-> Default: `(state) => state`109-110-Enables you to pick some of the state's fields to be stored in the storage.111-112-You could omit multiple fields using the following:113-114-```ts115-export const useBoundStore = create(116- persist(117- (set, get) => ({118- foo: 0,119- bar: 1,120- }),121- {122- // ...123- partialize: (state) =>124- Object.fromEntries(125- Object.entries(state).filter(([key]) => !['foo'].includes(key)),126- ),127- },128- ),129-)130-```131-132-Or you could allow only specific fields using the following:133-134-```ts135-export const useBoundStore = create(136- persist(137- (set, get) => ({138- foo: 0,139- bar: 1,140- }),141- {142- // ...143- partialize: (state) => ({ foo: state.foo }),144- },145- ),146-)147-```148-149-### `onRehydrateStorage`150-151-> Type: `(state: Object) => ((state?: Object, error?: Error) => void) | void`152-153-This option enables you to pass a listener function154-that will be called when the storage is hydrated.155-156-Example:157-158-```ts159-export const useBoundStore = create(160- persist(161- (set, get) => ({162- // ...163- }),164- {165- // ...166- onRehydrateStorage: (state) => {167- console.log('hydration starts')168-169- // optional170- return (state, error) => {171- if (error) {172- console.log('an error happened during hydration', error)173- } else {174- console.log('hydration finished')175- }176- }177- },178- },179- ),180-)181-```182-183-### `version`184-185-> Type: `number`186-187-> Default: `0`188-189-If you want to introduce a breaking change in your storage190-(e.g. renaming a field), you can specify a new version number.191-By default, if the version in the storage192-does not match the version in the code,193-the stored value won't be used.194-You can use the [migrate](#migrate) function (see below)195-to handle breaking changes in order to persist previously stored data.196-197-### `migrate`198-199-> Type: `(persistedState: Object, version: number) => Object | Promise<Object>`200-201-> Default: `(persistedState) => persistedState`202-203-You can use this option to handle versions migration.204-The migrate function takes the persisted state205-and the version number as arguments.206-It must return a state that is compliant207-to the latest version (the version in the code).208-209-For instance, if you want to rename a field, you can use the following:210-211-```ts212-export const useBoundStore = create(213- persist(214- (set, get) => ({215- newField: 0, // let's say this field was named otherwise in version 0216- }),217- {218- // ...219- version: 1, // a migration will be triggered if the version in the storage mismatches this one220- migrate: (persistedState, version) => {221- if (version === 0) {222- // if the stored value is in version 0, we rename the field to the new name223- persistedState.newField = persistedState.oldField224- delete persistedState.oldField225- }226-227- return persistedState228- },229- },230- ),231-)232-```233-234-### `merge`235-236-> Type: `(persistedState: Object, currentState: Object) => Object`237-238-> Default: `(persistedState, currentState) => ({ ...currentState, ...persistedState })`239-240-In some cases, you might want to use a custom merge function241-to merge the persisted value with the current state.242-243-By default, the middleware does a shallow merge.244-The shallow merge might not be enough245-if you have partially persisted nested objects.246-For instance, if the storage contains the following:247-248-```ts249-{250- foo: {251- bar: 0,252- }253-}254-```255-256-But your Zustand store contains:257-258-```ts259-{260- foo: {261- bar: 0,262- baz: 1,263- }264-}265-```266-267-The shallow merge will erase the `baz` field from the `foo` object.268-One way to fix this would be to give a custom deep merge function:269-270-```ts271-export const useBoundStore = create(272- persist(273- (set, get) => ({274- foo: {275- bar: 0,276- baz: 1,277- },278- }),279- {280- // ...281- merge: (persistedState, currentState) =>282- deepMerge(currentState, persistedState),283- },284- ),285-)286-```287-288-### `skipHydration`289-290-> Type: `boolean | undefined`291-292-> Default: `undefined`293-294-By default the store will be hydrated on initialization.295-296-In some applications you may need to control when the first hydration occurs.297-For example, in server-rendered apps.298-299-If you set `skipHydration`, the initial call for hydration isn't called,300-and it is left up to you to manually call `rehydrate()`.301-302-```ts303-export const useBoundStore = create(304- persist(305- () => ({306- count: 0,307- // ...308- }),309- {310- // ...311- skipHydration: true,312- },313- ),314-)315-```316-317-```tsx318-import { useBoundStore } from './path-to-store';319-320-export function StoreConsumer() {321- // hydrate persisted store after on mount322- useEffect(() => {323- useBoundStore.persist.rehydrate();324- }, [])325-326- return (327- //...328- )329-}330-```331-332-## API333-334-> Version: >=3.6.3335-336-The Persist API enables you to do a number of interactions337-with the Persist middleware338-from inside or outside of a React component.339-340-### `getOptions`341-342-> Type: `() => Partial<PersistOptions>`343-344-> Returns: Options of the Persist middleware345-346-For example, it can be used to obtain the storage name:347-348-```ts349-useBoundStore.persist.getOptions().name350-```351-352-### `setOptions`353-354-> Type: `(newOptions: Partial<PersistOptions>) => void`355-356-Changes the middleware options.357-Note that the new options will be merged with the current ones.358-359-For instance, this can be used to change the storage name:360-361-```ts362-useBoundStore.persist.setOptions({363- name: 'new-name',364-})365-```366-367-Or even to change the storage engine:368-369-```ts370-useBoundStore.persist.setOptions({371- storage: createJSONStorage(() => sessionStorage),372-})373-```374-375-### `clearStorage`376-377-> Type: `() => void`378-379-Clears everything stored under the [name](#name) key.380-381-```ts382-useBoundStore.persist.clearStorage()383-```384-385-### `rehydrate`386-387-> Type: `() => Promise<void>`388-389-In some cases, you might want to trigger the rehydration manually.390-This can be done by calling the `rehydrate` method.391-392-```ts393-await useBoundStore.persist.rehydrate()394-```395-396-### `hasHydrated`397-398-> Type: `() => boolean`399-400-This is a non-reactive getter to check401-if the storage has been hydrated402-(note that it updates when calling [`rehydrate`](#rehydrate)).403-404-```ts405-useBoundStore.persist.hasHydrated()406-```407-408-### `onHydrate`409-410-> Type: `(listener: (state) => void) => () => void`411-412-> Returns: Unsubscribe function413-414-This listener will be called when the hydration process starts.415-416-```ts417-const unsub = useBoundStore.persist.onHydrate((state) => {418- console.log('hydration starts')419-})420-421-// later on...422-unsub()423-```424-425-### `onFinishHydration`426-427-> Type: `(listener: (state) => void) => () => void`428-429-> Returns: Unsubscribe function430-431-This listener will be called when the hydration process ends.432-433-```ts434-const unsub = useBoundStore.persist.onFinishHydration((state) => {435- console.log('hydration finished')436-})437-438-// later on...439-unsub()440-```441-442-### `createJSONStorage`443-444-> Type: `(getStorage: () => StateStorage, options?: JsonStorageOptions) => StateStorage`445-446-> Returns: `PersistStorage`447-448-This helper function enables you to create a [`storage`](#storage) object which is useful when you want to use a custom storage engine.449-450-`getStorage` is a function that returns the storage engine with the properties `getItem`, `setItem`, and `removeItem`.451-452-`options` is an optional object that can be used to customize the serialization and deserialization of the data. `options.reviver` is a function that is passed to `JSON.parse` to deserialize the data. `options.replacer` is a function that is passed to `JSON.stringify` to serialize the data.453-454-```ts455-import { createJSONStorage } from 'zustand/middleware'456-457-const storage = createJSONStorage(() => sessionStorage, {458- reviver: (key, value) => {459- if (value && value.type === 'date') {460- return new Date(value)461- }462- return value463- },464- replacer: (key, value) => {465- // NOTE: the result of `.toJSON()` is passed to the466- // replacer function as value if is available so467- // a Date is always a `string` at this point468- if (key === 'someDate') return { type: 'date', value }469- return value470- },471-})472-```473-474-## Hydration and asynchronous storages475-476-To explain what is the "cost" of asynchronous storages,477-you need to understand what is hydration.478-479-In a nutshell, hydration is a process480-of retrieving persisted state from the storage481-and merging it with the current state.482-483-The Persist middleware does two kinds of hydration:484-synchronous and asynchronous.485-If the given storage is synchronous (e.g., `localStorage`),486-hydration will be done synchronously.487-On the other hand, if the given storage is asynchronous (e.g., `AsyncStorage`),488-hydration will be done asynchronously (shocking, I know!).489-490-But what's the catch?491-With synchronous hydration,492-the Zustand store will already have been hydrated at its creation.493-In contrast, with asynchronous hydration,494-the Zustand store will be hydrated later on, in a microtask.495-496-Why does it matter?497-Asynchronous hydration can cause some unexpected behaviors.498-For instance, if you use Zustand in a React app,499-the store will **not** be hydrated at the initial render.500-In cases where your app depends on the persisted value at page load,501-you might want to wait until502-the store has been hydrated before showing anything.503-For example, your app might think the user504-is not logged in because it's the default,505-but in reality the store has not been hydrated yet.506-507-If your app does depends on the persisted state at page load,508-see [_How can I check if my store has been hydrated_](#how-can-i-check-if-my-store-has-been-hydrated)509-in the [FAQ](#faq) section below.510-511-### Usage in Next.js512-513-NextJS uses Server Side Rendering, and it will compare the rendered component on the server with the one rendered on client.514-But since you are using data from browser to change your component, the two renders will differ and Next will throw a warning at you.515-516-The errors usually are:517-518-- Text content does not match server-rendered HTML519-- Hydration failed because the initial UI does not match what was rendered on the server520-- There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering521-522-To solve these errors, create a custom hook so that Zustand waits a little before changing your components.523-524-Create a file with the following:525-526-```ts527-// useStore.ts528-import { useState, useEffect } from 'react'529-530-const useStore = <T, F>(531- store: (callback: (state: T) => unknown) => unknown,532- callback: (state: T) => F,533-) => {534- const result = store(callback) as F535- const [data, setData] = useState<F>()536-537- useEffect(() => {538- setData(result)539- }, [result])540-541- return data542-}543-544-export default useStore545-```546-547-Now in your pages, you will use the hook a little bit differently:548-549-```ts550-// useBearStore.ts551-552-import { create } from 'zustand'553-import { persist } from 'zustand/middleware'554-555-// the store itself does not need any change556-export const useBearStore = create(557- persist(558- (set, get) => ({559- bears: 0,560- addABear: () => set({ bears: get().bears + 1 }),561- }),562- {563- name: 'food-storage',564- },565- ),566-)567-```568-569-```ts570-// yourComponent.tsx571-572-import useStore from './useStore'573-import { useBearStore } from './stores/useBearStore'574-575-const bears = useStore(useBearStore, (state) => state.bears)576-```577-578-Credits: [This reply to an issue](https://github.com/pmndrs/zustand/issues/938#issuecomment-1481801942), which points to [this blog post](https://dev.to/abdulsamad/how-to-use-zustands-persist-middleware-in-nextjs-4lb5).579-580-## FAQ581-582-### How can I check if my store has been hydrated583-584-There are a few different ways to do this.585-586-You can use the [`onRehydrateStorage`](#onrehydratestorage)587-listener function to update a field in the store:588-589-```ts590-const useBoundStore = create(591- persist(592- (set, get) => ({593- // ...594- _hasHydrated: false,595- setHasHydrated: (state) => {596- set({597- _hasHydrated: state598- });599- }600- }),601- {602- // ...603- onRehydrateStorage: (state) => {604- return () => state.setHasHydrated(true)605- }606- }607- )608-);609-610-export default function App() {611- const hasHydrated = useBoundStore(state => state._hasHydrated);612-613- if (!hasHydrated) {614- return <p>Loading...</p>615- }616-617- return (618- // ...619- );620-}621-```622-623-You can also create a custom `useHydration` hook:624-625-```ts626-const useBoundStore = create(persist(...))627-628-const useHydration = () => {629- const [hydrated, setHydrated] = useState(false)630-631- useEffect(() => {632- // Note: This is just in case you want to take into account manual rehydration.633- // You can remove the following line if you don't need it.634- const unsubHydrate = useBoundStore.persist.onHydrate(() => setHydrated(false))635-636- const unsubFinishHydration = useBoundStore.persist.onFinishHydration(() => setHydrated(true))637-638- setHydrated(useBoundStore.persist.hasHydrated())639-640- return () => {641- unsubHydrate()642- unsubFinishHydration()643- }644- }, [])645-646- return hydrated647-}648-```649-650-### How can I use a custom storage engine651-652-If the storage you want to use does not match the expected API, you can create your own storage:653-654-```ts655-import { create } from 'zustand'656-import { persist, createJSONStorage, StateStorage } from 'zustand/middleware'657-import { get, set, del } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.658-659-// Custom storage object660-const storage: StateStorage = {661- getItem: async (name: string): Promise<string | null> => {662- console.log(name, 'has been retrieved')663- return (await get(name)) || null664- },665- setItem: async (name: string, value: string): Promise<void> => {666- console.log(name, 'with value', value, 'has been saved')667- await set(name, value)668- },669- removeItem: async (name: string): Promise<void> => {670- console.log(name, 'has been deleted')671- await del(name)672- },673-}674-675-export const useBoundStore = create(676- persist(677- (set, get) => ({678- bears: 0,679- addABear: () => set({ bears: get().bears + 1 }),680- }),681- {682- name: 'food-storage', // unique name683- storage: createJSONStorage(() => storage),684- },685- ),686-)687-```688-689-If you're using a type that `JSON.stringify()` doesn't support, you'll need to write your own serialization/deserialization code. However, if this is tedious, you can use third-party libraries to serialize and deserialize different types of data.690-691-For example, [Superjson](https://github.com/blitz-js/superjson) can serialize data along with its type, allowing the data to be parsed back to its original type upon deserialization692-693-```ts694-import superjson from 'superjson' // can use anything: serialize-javascript, devalue, etc.695-import { PersistStorage } from 'zustand/middleware'696-697-interface BearState {698- bear: Map<string, string>699- fish: Set<string>700- time: Date701- query: RegExp702-}703-704-const storage: PersistStorage<BearState> = {705- getItem: (name) => {706- const str = localStorage.getItem(name)707- if (!str) return null708- return superjson.parse(str)709- },710- setItem: (name, value) => {711- localStorage.setItem(name, superjson.stringify(value))712- },713- removeItem: (name) => localStorage.removeItem(name),714-}715-716-const initialState: BearState = {717- bear: new Map(),718- fish: new Set(),719- time: new Date(),720- query: new RegExp(''),721-}722-723-export const useBearStore = create<BearState>()(724- persist(725- (set) => ({726- ...initialState,727- // ...728- }),729- {730- name: 'food-storage',731- storage,732- },733- ),734-)735-```736-737-### How can I rehydrate on storage event738-739-You can use the Persist API to create your own implementation,740-similar to the example below:741-742-```ts743-type StoreWithPersist = Mutate<StoreApi<State>, [["zustand/persist", unknown]]>744-745-export const withStorageDOMEvents = (store: StoreWithPersist) => {746- const storageEventCallback = (e: StorageEvent) => {747- if (e.key === store.persist.getOptions().name && e.newValue) {748- store.persist.rehydrate()749- }750- }751-752- window.addEventListener('storage', storageEventCallback)753-754- return () => {755- window.removeEventListener('storage', storageEventCallback)756- }757-}758-759-const useBoundStore = create(persist(...))760-withStorageDOMEvents(useBoundStore)761-```762-763-### How do I use it with TypeScript764-765-Basic typescript usage doesn't require anything special766-except for writing `create<State>()(...)` instead of `create(...)`.767-768-```tsx769-import { create } from 'zustand'770-import { persist, createJSONStorage } from 'zustand/middleware'771-772-interface MyState {773- bears: number774- addABear: () => void775-}776-777-export const useBearStore = create<MyState>()(778- persist(779- (set, get) => ({780- bears: 0,781- addABear: () => set({ bears: get().bears + 1 }),782- }),783- {784- name: 'food-storage', // name of item in the storage (must be unique)785- storage: createJSONStorage(() => sessionStorage), // (optional) by default the 'localStorage' is used786- partialize: (state) => ({ bears: state.bears }),787- },788- ),789-)790-```791-792-### How do I use it with Map and Set793-794-In order to persist object types such as `Map` and `Set`, they will need to be converted to JSON-serializable types such as an `Array` which can be done by defining a custom `storage` engine.795-796-Let's say your state uses `Map` to handle a list of `transactions`,797-then you can convert the `Map` into an `Array` in the `storage` prop which is shown below:798-799-```ts800-801-interface BearState {802- .803- .804- .805- transactions: Map<any>806-}807-808- storage: {809- getItem: (name) => {810- const str = localStorage.getItem(name);811- if (!str) return null;812- const existingValue = JSON.parse(str);813- return {814- ...existingValue,815- state: {816- ...existingValue.state,817- transactions: new Map(existingValue.state.transactions),818- }819- }820- },821- setItem: (name, newValue: StorageValue<BearState>) => {822- // functions cannot be JSON encoded823- const str = JSON.stringify({824- ...newValue,825- state: {826- ...newValue.state,827- transactions: Array.from(newValue.state.transactions.entries()),828- },829- })830- localStorage.setItem(name, str)831- },832- removeItem: (name) => localStorage.removeItem(name),833- },834-```deleted:docs/integrations/third-party-libraries.md-82 removed
1----2-title: Third-party Libraries3-nav: 194----5-6-Zustand provides bear necessities for state management.7-Although it is great for most projects,8-some users wish to extend the library's feature set.9-This can be done using third-party libraries created by the community.10-11-> Disclaimer: These libraries may have bugs, limited maintenance,12-> or other limitations, and are not officially recommended13-> by pmndrs or the Zustand maintainers.14-> This list aims to provide a good starting point15-> for someone looking to extend Zustand's feature set.16-17-- [@colorfy-software/zfy](https://colorfy-software.gitbook.io/zfy/) — 🧸 Useful helpers for state management in React with Zustand.18-- [@csark0812/zustand-expo-devtools](https://github.com/csark0812/zustand-expo-devtools) — 🧭 Connect Zustand to Redux DevTools in Expo + React Native using the official Expo DevTools plugin system.19-- [@csark0812/zustand-getters](https://github.com/csark0812/zustand-getters) — 🔄 Make JavaScript object getters reactive in Zustand stores — define derived values with `get propertyName()` and they automatically trigger subscription updates when accessed.20-- [@davstack/store](https://www.npmjs.com/package/@davstack/store) — A zustand store factory that auto generates selectors with get/set/use methods, supports inferred types, and makes global / local state management easy.21-- [@dhmk/zustand-lens](https://github.com/dhmk083/dhmk-zustand-lens) — Lens support for Zustand.22-- [@hpkv/zustand-multiplayer](https://github.com/hpkv-io/zustand-multiplayer/tree/main/packages/zustand-multiplayer) — HPKV multiplayer middleware for building realtime collaborative applications23-- [@liveblocks/zustand](https://github.com/liveblocks/liveblocks/tree/main/packages/liveblocks-zustand) — Liveblocks middleware to make your application multiplayer.24-- [@prncss-xyz/zustand-optics](https://github.com/prncss-xyz/zustand-optics) — An adapter for [optics-ts](https://github.com/akheron/optics-ts).25-- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook) — Automatic generation of Zustand hooks with Typescript support.26-- [derive-zustand](https://github.com/zustandjs/derive-zustand) — A function to create a derived Zustand store from other Zustand stores.27-- [geschichte](https://github.com/BowlingX/geschichte) — Zustand and Immer-based hook to manage query parameters.28-- [leiten-zustand](https://github.com/hecmatyar/leiten-zustand) — Cleans your store from boilerplate for requests and data transformation.29-- [leo-query](https://github.com/steaks/leo-query) — A simple library to connect async queries to Zustand stores.30-- [mobz](https://github.com/2A5F/Mobz) — Zustand-style MobX API.31-- [ngx-zustand](https://github.com/JoaoPauloLousada/ngx-zustand) — A Zustand adapter for Angular.32-- [persist-and-sync](https://github.com/mayank1513/persist-and-sync) — Zustand middleware to easily persist and sync Zustand state between tabs/windows/iframes with same origin.33-- [shared-zustand](https://github.com/Tom-Julux/shared-zustand) — Cross-tab state sharing for Zustand.34-- [simple-zustand-devtools](https://github.com/beerose/simple-zustand-devtools) — 🐻⚛️ Inspect your Zustand store in React DevTools.35-- [solid-zustand](https://github.com/wobsoriano/solid-zustand) — State management in Solid using Zustand.36-- [treeshakable](https://github.com/react18-tools/treeshakable) — A wrapper for library creators to avoid redundant store creation.37-- [use-broadcast-ts](https://github.com/Romainlg29/use-broadcast) — Zustand middleware to share state between tabs.38-- [use-post-message-ts](https://github.com/paulschoen/use-post-message) — Zustand middleware for sharing state between cross-origin iframes via postMessage browser method.39-- [use-zustand](https://github.com/zustandjs/use-zustand) — Another custom hook to use Zustand vanilla store.40-- [vue-zustand](https://github.com/wobsoriano/vue-zustand) — State management solution for Vue based on Zustand.41-- [zoov](https://github.com/InfiniteXyy/zoov) — State management solution based on Zustand with Module-like API.42-- [zubridge](https://github.com/goosewobbler/zubridge) — Use Zustand in cross-platform apps, seamlessly. Supports Electron & Tauri.43-- [zukeeper](https://github.com/oslabs-beta/Zukeeper) — Native devtools with state and action tracking, diffing, tree display, and time travel44-- [zundo](https://github.com/charkour/zundo) — 🍜 Undo and redo middleware for Zustand, enabling time-travel in your apps.45-- [zustand-ards](https://github.com/ivoilic/zustand-ards) — 💁 Simple opinionated utilities for example alternative selector formats and default shallow hooks46-- [zustand-async-slice](https://github.com/mym0404/zustand-async-slice) — Simple Zustand utility to create Async Slice. TypeScript Fully Supported 🖖47-- [zustand-boilerplate](https://github.com/sagiereder/zustand-boilerplate) — A tool that automatically generates getters, setters and more for your zustand store.48-- [zustand-computed](https://github.com/chrisvander/zustand-computed) — A Zustand middleware to create computed states.49-- [zustand-computed-state](https://github.com/yasintz/zustand-computed-state) — Simple middleware to add computed states.50-- [zustand-constate](https://github.com/ntvinhit/zustand-constate) — Context-based state management based on Zustand and taking ideas from Constate.51-- [zustand-context](https://github.com/fredericoo/zustand-context) — Create a zustand store in React Context, containing an initial value, or use it in your components with isolated, mockable instances.52-- [zustand-create-setter-fn](https://www.npmjs.com/package/zustand-create-setter-fn) — A fully type safe utility for Zustand that allows you to easily update state using React style `setState` functions (framework agnostic, doesn't require React).53-- [zustand-di](https://github.com/charkour/zustand-di) — use react props to init zustand stores54-- [zustand-forms](https://github.com/Conduct/zustand-forms) — Fast, type safe form states as Zustand stores.55-- [zustand-hash-storage](https://github.com/MartinGamesCZ/zustand-hash-storage) — Zustand middleware for saving state into URL hash, b64 encoded (can be configured) and debounce timer.56-- [zustand-injectors](https://github.com/zustandjs/zustand-injectors) — A sweet way to lazy load slices57-- [zustand-interval-persist](https://www.npmjs.com/package/zustand-interval-persist) — An enhancement for zustand that enables automatic saving of the store's state to the specified storage at regular interval.58-- [zustand-lit](https://github.com/ennjin/zustand-lit) — A zustand adapter for lit.js (LitElement)59-- [zustand-middleware-computed-state](https://github.com/cmlarsen/zustand-middleware-computed-state) — A dead simple middleware for adding computed state to Zustand.60-- [zustand-middleware-xstate](https://github.com/biowaffeln/zustand-middleware-xstate) — A middleware for putting XState state machines into a global Zustand store.61-- [zustand-middleware-yjs](https://github.com/joebobmiles/zustand-middleware-yjs) — A middleware for synchronizing Zustand stores with Yjs.62-- [zustand-mmkv-storage](https://github.com/1mehdifaraji/zustand-mmkv-storage) — Fast, lightweight MMKV storage adapter for Zustand persist middleware in React Native.63-- [zustand-multi-persist](https://github.com/mooalot/zustand-multi-persist) — A middleware for persisting and rehydrating state to multiple storage engines.64-- [zustand-mutable](https://github.com/zustandjs/zustand-mutable) — A sweet way to use immer-like mutable updates.65-- [zustand-namespaces](https://github.com/mooalot/zustand-namespaces) — One store to rule them all. Namespaced Zustand stores.66-- [zustand-persist](https://github.com/roadmanfong/zustand-persist) — A middleware for persisting and rehydrating state.67-- [zustand-pub](https://github.com/AwesomeDevin/zustand-pub) — Cross-Application/Cross-Framework State Management And Sharing based on zustand and zustand-vue for React/Vue.68-- [zustand-querystring](https://github.com/nitedani/zustand-querystring) — A Zustand middleware that syncs the store with the querystring.69-- [zustand-rx](https://github.com/patdx/zustand-rx) — A Zustand middleware enabling you to subscribe to a store as an RxJS Observable.70-- [zustand-saga](https://github.com/Nowsta/zustand-saga) — A Zustand middleware for redux-saga (minus redux).71-- [zustand-slices](https://github.com/zustandjs/zustand-slices) — A slice utility for Zustand.72-- [zustand-store-addons](https://github.com/Diablow/zustand-store-addons) — React state management addons for Zustand.73-- [zustand-sync-tabs](https://github.com/mayank1513/zustand-sync-tabs) — Zustand middleware to easily sync Zustand state between tabs/windows/iframes with same origin.74-- [zustand-utils](https://www.npmjs.com/package/zustand-utils) — Utilities for Zustand — a `createContext` replacement, a devtools wrapper, and a store-updater factory function.75-- [zustand-valtio](https://github.com/zustandjs/zustand-valtio) — A sweet combination of Zustand and Valtio76-- [zustand-vue](https://github.com/AwesomeDevin/zustand-vue) — State management for vue (Vue3 / Vue2) based on zustand.77-- [zustand-x](https://github.com/udecode/zustand-x) — Zustand store factory for a best-in-class developer experience.78-- [zustand-xs](https://github.com/zustandjs/zustand-xs) — XState/store compabile middleware for Zustand79-- [zustand-yjs](https://github.com/tandem-pt/zustand-yjs) — Zustand stores for Yjs structures.80-- [zusteller](https://github.com/timkindberg/zusteller) — Your global state savior. "Just hooks" + Zustand.81-- [zustorm](https://github.com/mooalot/zustorm) — A simple and powerful form library for Zustand.82-- [zusty](https://github.com/oslabs-beta/Zusty) — Zustand tool to assist debugging with time travel, action logs, state snapshots, store view, render time metrics and state component tree.added:docs/learn/getting-started/comparison.md+483 added
1+---2+title: Comparison3+description: How Zustand stacks up against similar libraries4+nav: 25+---6+7+Zustand is one of many state management libraries for React.8+On this page we will discuss Zustand9+in comparison to some of these libraries,10+including Redux, Valtio, Jotai, and Recoil.11+12+Each library has its own strengths and weaknesses,13+and we will compare key differences and similarities between each.14+15+## Redux16+17+### State Model (vs Redux)18+19+Conceptually, Zustand and Redux are quite similar,20+both are based on an immutable state model.21+However, Redux requires your app to be wrapped22+in context providers; Zustand does not.23+24+**Zustand**25+26+```ts27+import { create } from 'zustand'28+29+type State = {30+ count: number31+}32+33+type Actions = {34+ increment: (qty: number) => void35+ decrement: (qty: number) => void36+}37+38+const useCountStore = create<State & Actions>((set) => ({39+ count: 0,40+ increment: (qty: number) => set((state) => ({ count: state.count + qty })),41+ decrement: (qty: number) => set((state) => ({ count: state.count - qty })),42+}))43+```44+45+```ts46+import { create } from 'zustand'47+48+type State = {49+ count: number50+}51+52+type Action = {53+ type: 'increment' | 'decrement'54+ qty: number55+}56+57+type Actions = {58+ dispatch: (action: Action) => void59+}60+61+const countReducer = (state: State, action: Action) => {62+ switch (action.type) {63+ case 'increment':64+ return { count: state.count + action.qty }65+ case 'decrement':66+ return { count: state.count - action.qty }67+ default:68+ return state69+ }70+}71+72+const useCountStore = create<State & Actions>((set) => ({73+ count: 0,74+ dispatch: (action: Action) => set((state) => countReducer(state, action)),75+}))76+```77+78+**Redux**79+80+```ts81+import { createStore } from 'redux'82+import { useSelector, useDispatch } from 'react-redux'83+84+type State = {85+ count: number86+}87+88+type Action = {89+ type: 'increment' | 'decrement'90+ qty: number91+}92+93+const countReducer = (state: State, action: Action) => {94+ switch (action.type) {95+ case 'increment':96+ return { count: state.count + action.qty }97+ case 'decrement':98+ return { count: state.count - action.qty }99+ default:100+ return state101+ }102+}103+104+const countStore = createStore(countReducer)105+```106+107+```ts108+import { createSlice, configureStore } from '@reduxjs/toolkit'109+110+const countSlice = createSlice({111+ name: 'count',112+ initialState: { value: 0 },113+ reducers: {114+ incremented: (state, qty: number) => {115+ // Redux Toolkit does not mutate the state, it uses the Immer library116+ // behind scenes, allowing us to have something called "draft state".117+ state.value += qty118+ },119+ decremented: (state, qty: number) => {120+ state.value -= qty121+ },122+ },123+})124+125+const countStore = configureStore({ reducer: countSlice.reducer })126+```127+128+### Render Optimization (vs Redux)129+130+When it comes to render optimizations within your app,131+there are no major differences in approach between Zustand and Redux.132+In both libraries it is recommended133+that you manually apply render optimizations by using selectors.134+135+**Zustand**136+137+```ts138+import { create } from 'zustand'139+140+type State = {141+ count: number142+}143+144+type Actions = {145+ increment: (qty: number) => void146+ decrement: (qty: number) => void147+}148+149+const useCountStore = create<State & Actions>((set) => ({150+ count: 0,151+ increment: (qty: number) => set((state) => ({ count: state.count + qty })),152+ decrement: (qty: number) => set((state) => ({ count: state.count - qty })),153+}))154+155+const Component = () => {156+ const count = useCountStore((state) => state.count)157+ const increment = useCountStore((state) => state.increment)158+ const decrement = useCountStore((state) => state.decrement)159+ // ...160+}161+```162+163+**Redux**164+165+```ts166+import { createStore } from 'redux'167+import { useSelector, useDispatch } from 'react-redux'168+169+type State = {170+ count: number171+}172+173+type Action = {174+ type: 'increment' | 'decrement'175+ qty: number176+}177+178+const countReducer = (state: State, action: Action) => {179+ switch (action.type) {180+ case 'increment':181+ return { count: state.count + action.qty }182+ case 'decrement':183+ return { count: state.count - action.qty }184+ default:185+ return state186+ }187+}188+189+const countStore = createStore(countReducer)190+191+const Component = () => {192+ const count = useSelector((state) => state.count)193+ const dispatch = useDispatch()194+ // ...195+}196+```197+198+```ts199+import { useSelector } from 'react-redux'200+import type { TypedUseSelectorHook } from 'react-redux'201+import { createSlice, configureStore } from '@reduxjs/toolkit'202+203+const countSlice = createSlice({204+ name: 'count',205+ initialState: { value: 0 },206+ reducers: {207+ incremented: (state, qty: number) => {208+ // Redux Toolkit does not mutate the state, it uses the Immer library209+ // behind scenes, allowing us to have something called "draft state".210+ state.value += qty211+ },212+ decremented: (state, qty: number) => {213+ state.value -= qty214+ },215+ },216+})217+218+const countStore = configureStore({ reducer: countSlice.reducer })219+220+const useAppSelector: TypedUseSelectorHook<typeof countStore.getState> =221+ useSelector222+223+const useAppDispatch: () => typeof countStore.dispatch = useDispatch224+225+const Component = () => {226+ const count = useAppSelector((state) => state.count.value)227+ const dispatch = useAppDispatch()228+ // ...229+}230+```231+232+## Valtio233+234+### State Model (vs Valtio)235+236+Zustand and Valtio approach state management237+in a fundamentally different way.238+Zustand is based on the **immutable** state model,239+while Valtio is based on the **mutable** state model.240+241+**Zustand**242+243+```ts244+import { create } from 'zustand'245+246+type State = {247+ obj: { count: number }248+}249+250+const store = create<State>(() => ({ obj: { count: 0 } }))251+252+store.setState((prev) => ({ obj: { count: prev.obj.count + 1 } }))253+```254+255+**Valtio**256+257+```ts258+import { proxy } from 'valtio'259+260+const state = proxy({ obj: { count: 0 } })261+262+state.obj.count += 1263+```264+265+### Render Optimization (vs Valtio)266+267+The other difference between Zustand and Valtio268+is Valtio makes render optimizations through property access.269+However, with Zustand, it is recommended that270+you manually apply render optimizations by using selectors.271+272+**Zustand**273+274+```ts275+import { create } from 'zustand'276+277+type State = {278+ count: number279+}280+281+const useCountStore = create<State>(() => ({282+ count: 0,283+}))284+285+const Component = () => {286+ const count = useCountStore((state) => state.count)287+ // ...288+}289+```290+291+**Valtio**292+293+```ts294+import { proxy, useSnapshot } from 'valtio'295+296+const state = proxy({297+ count: 0,298+})299+300+const Component = () => {301+ const { count } = useSnapshot(state)302+ // ...303+}304+```305+306+## Jotai307+308+### State Model (vs Jotai)309+310+There is one major difference between Zustand and Jotai.311+Zustand is a single store,312+while Jotai consists of primitive atoms that can be composed together.313+314+**Zustand**315+316+```ts317+import { create } from 'zustand'318+319+type State = {320+ count: number321+}322+323+type Actions = {324+ updateCount: (325+ countCallback: (count: State['count']) => State['count'],326+ ) => void327+}328+329+const useCountStore = create<State & Actions>((set) => ({330+ count: 0,331+ updateCount: (countCallback) =>332+ set((state) => ({ count: countCallback(state.count) })),333+}))334+```335+336+**Jotai**337+338+```ts339+import { atom } from 'jotai'340+341+const countAtom = atom<number>(0)342+```343+344+### Render Optimization (vs Jotai)345+346+Jotai achieves render optimizations through atom dependency.347+However, with Zustand it is recommended that348+you manually apply render optimizations by using selectors.349+350+**Zustand**351+352+```ts353+import { create } from 'zustand'354+355+type State = {356+ count: number357+}358+359+type Actions = {360+ updateCount: (361+ countCallback: (count: State['count']) => State['count'],362+ ) => void363+}364+365+const useCountStore = create<State & Actions>((set) => ({366+ count: 0,367+ updateCount: (countCallback) =>368+ set((state) => ({ count: countCallback(state.count) })),369+}))370+371+const Component = () => {372+ const count = useCountStore((state) => state.count)373+ const updateCount = useCountStore((state) => state.updateCount)374+ // ...375+}376+```377+378+**Jotai**379+380+```ts381+import { atom, useAtom } from 'jotai'382+383+const countAtom = atom<number>(0)384+385+const Component = () => {386+ const [count, updateCount] = useAtom(countAtom)387+ // ...388+}389+```390+391+## Recoil392+393+### State Model (vs Recoil)394+395+The difference between Zustand and Recoil396+is similar to that between Zustand and Jotai.397+Recoil depends on atom string keys398+instead of atom object referential identities.399+Additionally, Recoil needs to wrap your app in a context provider.400+401+**Zustand**402+403+```ts404+import { create } from 'zustand'405+406+type State = {407+ count: number408+}409+410+type Actions = {411+ setCount: (countCallback: (count: State['count']) => State['count']) => void412+}413+414+const useCountStore = create<State & Actions>((set) => ({415+ count: 0,416+ setCount: (countCallback) =>417+ set((state) => ({ count: countCallback(state.count) })),418+}))419+```420+421+**Recoil**422+423+```ts424+import { atom } from 'recoil'425+426+const count = atom({427+ key: 'count',428+ default: 0,429+})430+```431+432+### Render Optimization (vs Recoil)433+434+Similar to previous optimization comparisons,435+Recoil makes render optimizations through atom dependency.436+Whereas with Zustand, it is recommended that437+you manually apply render optimizations by using selectors.438+439+**Zustand**440+441+```ts442+import { create } from 'zustand'443+444+type State = {445+ count: number446+}447+448+type Actions = {449+ setCount: (countCallback: (count: State['count']) => State['count']) => void450+}451+452+const useCountStore = create<State & Actions>((set) => ({453+ count: 0,454+ setCount: (countCallback) =>455+ set((state) => ({ count: countCallback(state.count) })),456+}))457+458+const Component = () => {459+ const count = useCountStore((state) => state.count)460+ const setCount = useCountStore((state) => state.setCount)461+ // ...462+}463+```464+465+**Recoil**466+467+```ts468+import { atom, useRecoilState } from 'recoil'469+470+const countAtom = atom({471+ key: 'count',472+ default: 0,473+})474+475+const Component = () => {476+ const [count, setCount] = useRecoilState(countAtom)477+ // ...478+}479+```480+481+## Npm Downloads Trend482+483+- [Npm Downloads Trend of State Management Libraries for React](https://npm-stat.com/charts.html?package=zustand&package=jotai&package=valtio&package=%40reduxjs%2Ftoolkit&package=recoil)added:docs/learn/getting-started/introduction.md+72 added
1+---2+title: Introduction3+description: How to use Zustand4+nav: 15+---6+7+<div class="flex justify-center mb-4">8+ <img src="/bear.jpg" alt="Logo Zustand" />9+</div>10+11+A small, fast, and scalable bearbones state management solution.12+Zustand has a comfy API based on hooks.13+It isn't boilerplatey or opinionated,14+but has enough convention to be explicit and flux-like.15+16+Don't disregard it because it's cute, it has claws!17+Lots of time was spent to deal with common pitfalls,18+like the dreaded [zombie child problem],19+[React concurrency], and [context loss]20+between mixed renderers.21+It may be the one state manager in the React space that gets all of these right.22+23+You can try a live demo [here](https://codesandbox.io/s/dazzling-moon-itop4).24+25+[zombie child problem]: https://react-redux.js.org/api/hooks#stale-props-and-zombie-children26+[react concurrency]: https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md27+[context loss]: https://github.com/facebook/react/issues/1333228+29+## Installation30+31+Zustand is available as a package on NPM for use:32+33+```bash34+# NPM35+npm install zustand36+# Or, use any package manager of your choice.37+```38+39+## First create a store40+41+Your store is a hook!42+You can put anything in it: primitives, objects, functions.43+The `set` function _merges_ state.44+45+```js46+import { create } from 'zustand'47+48+const useBear = create((set) => ({49+ bears: 0,50+ increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),51+ removeAllBears: () => set({ bears: 0 }),52+ updateBears: (newBears) => set({ bears: newBears }),53+}))54+```55+56+## Then bind your components, and that's it!57+58+You can use the hook anywhere, without the need of providers.59+Select your state and the consuming component60+will re-render when that state changes.61+62+```jsx63+function BearCounter() {64+ const bears = useBear((state) => state.bears)65+ return <h1>{bears} bears around here...</h1>66+}67+68+function Controls() {69+ const increasePopulation = useBear((state) => state.increasePopulation)70+ return <button onClick={increasePopulation}>one up</button>71+}72+```added:docs/learn/guides/advanced-typescript.md+542 added
1+---2+title: Advanced TypeScript Guide3+nav: 134+---5+6+## Basic usage7+8+The difference when using TypeScript is that instead of writing `create(...)`, you have to write `create<T>()(...)` (notice the extra parentheses `()` too along with the type parameter) where `T` is the type of the state to annotate it. For example:9+10+```ts11+import { create } from 'zustand'12+13+interface BearState {14+ bears: number15+ increase: (by: number) => void16+}17+18+const useBearStore = create<BearState>()((set) => ({19+ bears: 0,20+ increase: (by) => set((state) => ({ bears: state.bears + by })),21+}))22+```23+24+<details>25+ <summary>Why can't we simply infer the type from the initial state?</summary>26+27+ <br/>28+29+**TLDR**: Because state generic `T` is invariant.30+31+Consider this minimal version `create`:32+33+```ts34+declare const create: <T>(f: (get: () => T) => T) => T35+36+const x = create((get) => ({37+ foo: 0,38+ bar: () => get(),39+}))40+// `x` is inferred as `unknown` instead of41+// interface X {42+// foo: number,43+// bar: () => X44+// }45+```46+47+Here, if you look at the type of `f` in `create`, i.e. `(get: () => T) => T`, it "gives" `T` via return (making it covariant), but it also "takes" `T` via `get` (making it contravariant). "So where does `T` come from?" TypeScript wonders. It's like that chicken or egg problem. At the end TypeScript, gives up and infers `T` as `unknown`.48+49+So, as long as the generic to be inferred is invariant (i.e. both covariant and contravariant), TypeScript will be unable to infer it. Another simple example would be this:50+51+```ts52+const createFoo = {} as <T>(f: (t: T) => T) => T53+const x = createFoo((_) => 'hello')54+```55+56+Here again, `x` is `unknown` instead of `string`.57+58+ <details>59+ <summary>More about the inference (just for the people curious and interested in TypeScript)</summary>60+61+In some sense this inference failure is not a problem because a value of type `<T>(f: (t: T) => T) => T` cannot be written. That is to say you can't write the real runtime implementation of `createFoo`. Let's try it:62+63+```js64+const createFoo = (f) => f(/* ? */)65+```66+67+`createFoo` needs to return the return value of `f`. And to do that we first have to call `f`. And to call it we have to pass a value of type `T`. And to pass a value of type `T` we first have to produce it. But how can we produce a value of type `T` when we don't even know what `T` is? The only way to produce a value of type `T` is to call `f`, but then to call `f` itself we need a value of type `T`. So you see it's impossible to actually write `createFoo`.68+69+So what we're saying is, the inference failure in case of `createFoo` is not really a problem because it's impossible to implement `createFoo`. But what about the inference failure in case of `create`? That also is not really a problem because it's impossible to implement `create` too. Wait a minute, if it's impossible to implement `create` then how does Zustand implement it? The answer is, it doesn't.70+71+Zustand lies that it implemented `create`'s type, it implemented only the most part of it. Here's a simple proof by showing unsoundness. Consider the following code:72+73+```ts74+import { create } from 'zustand'75+76+const useBoundStore = create<{ foo: number }>()((_, get) => ({77+ foo: get().foo,78+}))79+```80+81+This code compiles. But if we run it, we'll get an exception: "Uncaught TypeError: Cannot read properties of undefined (reading 'foo')". This is because `get` would return `undefined` before the initial state is created (hence you shouldn't call `get` when creating the initial state). The types promise that `get` will never return `undefined` but it does initially, which means Zustand failed to implement it.82+83+And of course Zustand failed because it's impossible to implement `create` the way types promise (in the same way it's impossible to implement `createFoo`). In other words we don't have a type to express the actual `create` we have implemented. We can't type `get` as `() => T | undefined` because it would cause inconvenience and it still won't be correct as `get` is indeed `() => T` eventually, just if called synchronously it would be `() => undefined`. What we need is some kind of TypeScript feature that allows us to type `get` as `(() => T) & WhenSync<() => undefined>`, which of course is extremely far-fetched.84+85+So we have two problems: lack of inference and unsoundness. Lack of inference can be solved if TypeScript can improve its inference for invariants. And unsoundness can be solved if TypeScript introduces something like `WhenSync`. To work around lack of inference we manually annotate the state type. And we can't work around unsoundness, but it's not a big deal because it's not much, calling `get` synchronously anyway doesn't make sense.86+87+</details>88+89+</details>90+91+<details>92+ <summary>Why the currying `()(...)`?</summary>93+94+ <br/>95+96+**TLDR**: It is a workaround for [microsoft/TypeScript#10571](https://github.com/microsoft/TypeScript/issues/10571).97+98+Imagine you have a scenario like this:99+100+```ts101+declare const withError: <T, E>(102+ p: Promise<T>,103+) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>104+declare const doSomething: () => Promise<string>105+106+const main = async () => {107+ let [error, value] = await withError(doSomething())108+}109+```110+111+Here, `T` is inferred to be a `string` and `E` is inferred to be `unknown`. You might want to annotate `E` as `Foo`, because you are certain of the shape of error `doSomething()` would throw. However, you can't do that. You can either pass all generics or none. Along with annotating `E` as `Foo`, you will also have to annotate `T` as `string` even though it gets inferred anyway. The solution is to make a curried version of `withError` that does nothing at runtime. Its purpose is to just allow you annotate `E`.112+113+```ts114+declare const withError: {115+ <E>(): <T>(116+ p: Promise<T>,117+ ) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>118+ <T, E>(119+ p: Promise<T>,120+ ): Promise<[error: undefined, value: T] | [error: E, value: undefined]>121+}122+declare const doSomething: () => Promise<string>123+interface Foo {124+ bar: string125+}126+127+const main = async () => {128+ let [error, value] = await withError<Foo>()(doSomething())129+}130+```131+132+This way, `T` gets inferred and you get to annotate `E`. Zustand has the same use case when we want to annotate the state (the first type parameter) but allow other parameters to get inferred.133+134+</details>135+136+Alternatively, you can also use `combine`, which infers the state so that you do not need to type it.137+138+```ts139+import { create } from 'zustand'140+import { combine } from 'zustand/middleware'141+142+const useBearStore = create(143+ combine({ bears: 0 }, (set) => ({144+ increase: (by: number) => set((state) => ({ bears: state.bears + by })),145+ })),146+)147+```148+149+<details>150+ <summary>Be a little careful</summary>151+152+ <br/>153+154+We achieve the inference by lying a little in the types of `set`, `get`, and `store` that you receive as parameters. The lie is that they're typed as if the state is the first parameter, when in fact the state is the shallow-merge (`{ ...a, ...b }`) of both first parameter and the second parameter's return. For example, `get` from the second parameter has type `() => { bears: number }` and that is a lie as it should be `() => { bears: number, increase: (by: number) => void }`. And `useBearStore` still has the correct type; for example, `useBearStore.getState` is typed as `() => { bears: number, increase: (by: number) => void }`.155+156+It isn't really a lie because `{ bears: number }` is still a subtype of `{ bears: number, increase: (by: number) => void }`. Therefore, there will be no problem in most cases. You should just be careful while using replace. For example, `set({ bears: 0 }, true)` would compile but will be unsound as it will delete the `increase` function. Another instance where you should be careful is if you use `Object.keys`. `Object.keys(get())` will return `["bears", "increase"]` and not `["bears"]`. The return type of `get` can make you fall for these mistakes.157+158+`combine` trades off a little type-safety for the convenience of not having to write a type for state. Hence, you should use `combine` accordingly. It is fine in most cases and you can use it conveniently.159+160+</details>161+162+Note that we don't use the curried version when using `combine` because `combine` "creates" the state. When using a middleware that creates the state, it isn't necessary to use the curried version because the state now can be inferred. Another middleware that creates state is `redux`. So when using `combine`, `redux`, or any other custom middleware that creates the state, we don't recommend using the curried version.163+164+If you want to infer state type also outside of state declaration, you can use the `ExtractState` type helper:165+166+```ts167+import { create, ExtractState } from 'zustand'168+import { combine } from 'zustand/middleware'169+170+type BearState = ExtractState<typeof useBearStore>171+172+const useBearStore = create(173+ combine({ bears: 0 }, (set) => ({174+ increase: (by: number) => set((state) => ({ bears: state.bears + by })),175+ })),176+)177+```178+179+## Using middlewares180+181+You do not have to do anything special to use middlewares in TypeScript.182+183+```ts184+import { create } from 'zustand'185+import { devtools, persist } from 'zustand/middleware'186+187+interface BearState {188+ bears: number189+ increase: (by: number) => void190+}191+192+const useBearStore = create<BearState>()(193+ devtools(194+ persist(195+ (set) => ({196+ bears: 0,197+ increase: (by) => set((state) => ({ bears: state.bears + by })),198+ }),199+ { name: 'bearStore' },200+ ),201+ ),202+)203+```204+205+Just make sure you are using them immediately inside `create` so as to make the contextual inference work. Doing something even remotely fancy like the following `myMiddlewares` would require more advanced types.206+207+```ts208+import { create } from 'zustand'209+import { devtools, persist } from 'zustand/middleware'210+211+const myMiddlewares = (f) => devtools(persist(f, { name: 'bearStore' }))212+213+interface BearState {214+ bears: number215+ increase: (by: number) => void216+}217+218+const useBearStore = create<BearState>()(219+ myMiddlewares((set) => ({220+ bears: 0,221+ increase: (by) => set((state) => ({ bears: state.bears + by })),222+ })),223+)224+```225+226+Also, we recommend using `devtools` middleware as last as possible. For example, when you use it with `immer` as a middleware, it should be `devtools(immer(...))` and not `immer(devtools(...))`. This is because`devtools` mutates the `setState` and adds a type parameter on it, which could get lost if other middlewares (like `immer`) also mutate `setState` before `devtools`. Hence using `devtools` at the end makes sure that no middlewares mutate `setState` before it.227+228+## Authoring middlewares and advanced usage229+230+Imagine you had to write this hypothetical middleware.231+232+```ts233+import { create } from 'zustand'234+235+const foo = (f, bar) => (set, get, store) => {236+ store.foo = bar237+ return f(set, get, store)238+}239+240+const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))241+console.log(useBearStore.foo.toUpperCase())242+```243+244+Zustand middlewares can mutate the store. But how could we possibly encode the mutation on the type-level? That is to say how could we type `foo` so that this code compiles?245+246+For a usual statically typed language, this is impossible. But thanks to TypeScript, Zustand has something called a "higher-kinded mutator" that makes this possible. If you are dealing with complex type problems, like typing a middleware or using the `StateCreator` type, you will have to understand this implementation detail. For this, you can [check out #710](https://github.com/pmndrs/zustand/issues/710).247+248+If you are eager to know what the answer is to this particular problem then you can [see it here](#middleware-that-changes-the-store-type).249+250+### Handling Dynamic `replace` Flag251+252+If the value of the `replace` flag is not known at compile time and is determined dynamically, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:253+254+```ts255+const replaceFlag = Math.random() > 0.5256+const args = [{ bears: 5 }, replaceFlag] as Parameters<257+ typeof useBearStore.setState258+>259+store.setState(...args)260+```261+262+#### Example with `as Parameters` Workaround263+264+```ts265+import { create } from 'zustand'266+267+interface BearState {268+ bears: number269+ increase: (by: number) => void270+}271+272+const useBearStore = create<BearState>()((set) => ({273+ bears: 0,274+ increase: (by) => set((state) => ({ bears: state.bears + by })),275+}))276+277+const replaceFlag = Math.random() > 0.5278+const args = [{ bears: 5 }, replaceFlag] as Parameters<279+ typeof useBearStore.setState280+>281+useBearStore.setState(...args) // Using the workaround282+```283+284+By following this approach, you can ensure that your code handles dynamic `replace` flags without encountering type issues.285+286+## Common recipes287+288+### Middleware that doesn't change the store type289+290+```ts291+import { create, StateCreator, StoreMutatorIdentifier } from 'zustand'292+293+type Logger = <294+ T,295+ Mps extends [StoreMutatorIdentifier, unknown][] = [],296+ Mcs extends [StoreMutatorIdentifier, unknown][] = [],297+>(298+ f: StateCreator<T, Mps, Mcs>,299+ name?: string,300+) => StateCreator<T, Mps, Mcs>301+302+type LoggerImpl = <T>(303+ f: StateCreator<T, [], []>,304+ name?: string,305+) => StateCreator<T, [], []>306+307+const loggerImpl: LoggerImpl = (f, name) => (set, get, store) => {308+ const loggedSet: typeof set = (...a) => {309+ set(...(a as Parameters<typeof set>))310+ console.log(...(name ? [`${name}:`] : []), get())311+ }312+ const setState = store.setState313+ store.setState = (...a) => {314+ setState(...(a as Parameters<typeof setState>))315+ console.log(...(name ? [`${name}:`] : []), store.getState())316+ }317+318+ return f(loggedSet, get, store)319+}320+321+export const logger = loggerImpl as unknown as Logger322+323+// ---324+325+const useBearStore = create<BearState>()(326+ logger(327+ (set) => ({328+ bears: 0,329+ increase: (by) => set((state) => ({ bears: state.bears + by })),330+ }),331+ 'bear-store',332+ ),333+)334+```335+336+### Middleware that changes the store type337+338+```ts339+import {340+ create,341+ StateCreator,342+ StoreMutatorIdentifier,343+ Mutate,344+ StoreApi,345+} from 'zustand'346+347+type Foo = <348+ T,349+ A,350+ Mps extends [StoreMutatorIdentifier, unknown][] = [],351+ Mcs extends [StoreMutatorIdentifier, unknown][] = [],352+>(353+ f: StateCreator<T, [...Mps, ['foo', A]], Mcs>,354+ bar: A,355+) => StateCreator<T, Mps, [['foo', A], ...Mcs]>356+357+declare module 'zustand' {358+ interface StoreMutators<S, A> {359+ foo: Write<Cast<S, object>, { foo: A }>360+ }361+}362+363+type FooImpl = <T, A>(364+ f: StateCreator<T, [], []>,365+ bar: A,366+) => StateCreator<T, [], []>367+368+const fooImpl: FooImpl = (f, bar) => (set, get, _store) => {369+ type T = ReturnType<typeof f>370+ type A = typeof bar371+372+ const store = _store as Mutate<StoreApi<T>, [['foo', A]]>373+ store.foo = bar374+ return f(set, get, _store)375+}376+377+export const foo = fooImpl as unknown as Foo378+379+type Write<T extends object, U extends object> = Omit<T, keyof U> & U380+381+type Cast<T, U> = T extends U ? T : U382+383+// ---384+385+const useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))386+console.log(useBearStore.foo.toUpperCase())387+```388+389+### `create` without curried workaround390+391+The recommended way to use `create` is using the curried workaround like so: `create<T>()(...)`. This is because it enables you to infer the store type. But if for some reason you do not want to use the workaround, you can pass the type parameters like the following. Note that in some cases, this acts as an assertion instead of annotation, so we don't recommend it.392+393+```ts394+import { create } from "zustand"395+396+interface BearState {397+ bears: number398+ increase: (by: number) => void399+}400+401+const useBearStore = create<402+ BearState,403+ [404+ ['zustand/persist', BearState],405+ ['zustand/devtools', never]406+ ]407+>(devtools(persist((set) => ({408+ bears: 0,409+ increase: (by) => set((state) => ({ bears: state.bears + by })),410+}), { name: 'bearStore' }))411+```412+413+### Slices pattern414+415+```ts416+import { create, StateCreator } from 'zustand'417+418+interface BearSlice {419+ bears: number420+ addBear: () => void421+ eatFish: () => void422+}423+424+interface FishSlice {425+ fishes: number426+ addFish: () => void427+}428+429+interface SharedSlice {430+ addBoth: () => void431+ getBoth: () => number432+}433+434+const createBearSlice: StateCreator<435+ BearSlice & FishSlice,436+ [],437+ [],438+ BearSlice439+> = (set) => ({440+ bears: 0,441+ addBear: () => set((state) => ({ bears: state.bears + 1 })),442+ eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),443+})444+445+const createFishSlice: StateCreator<446+ BearSlice & FishSlice,447+ [],448+ [],449+ FishSlice450+> = (set) => ({451+ fishes: 0,452+ addFish: () => set((state) => ({ fishes: state.fishes + 1 })),453+})454+455+const createSharedSlice: StateCreator<456+ BearSlice & FishSlice,457+ [],458+ [],459+ SharedSlice460+> = (set, get) => ({461+ addBoth: () => {462+ // you can reuse previous methods463+ get().addBear()464+ get().addFish()465+ // or do them from scratch466+ // set((state) => ({ bears: state.bears + 1, fishes: state.fishes + 1 })467+ },468+ getBoth: () => get().bears + get().fishes,469+})470+471+const useBoundStore = create<BearSlice & FishSlice & SharedSlice>()((...a) => ({472+ ...createBearSlice(...a),473+ ...createFishSlice(...a),474+ ...createSharedSlice(...a),475+}))476+```477+478+A detailed explanation on the slices pattern can be found [here](./slices-pattern.md).479+480+If you have some middlewares then replace `StateCreator<MyState, [], [], MySlice>` with `StateCreator<MyState, Mutators, [], MySlice>`. For example, if you are using `devtools` then it will be `StateCreator<MyState, [["zustand/devtools", never]], [], MySlice>`. See the ["Middlewares and their mutators reference"](#middlewares-and-their-mutators-reference) section for a list of all mutators.481+482+### Bounded `useStore` hook for vanilla stores483+484+```ts485+import { useStore } from 'zustand'486+import { createStore } from 'zustand/vanilla'487+488+interface BearState {489+ bears: number490+ increase: (by: number) => void491+}492+493+const bearStore = createStore<BearState>()((set) => ({494+ bears: 0,495+ increase: (by) => set((state) => ({ bears: state.bears + by })),496+}))497+498+function useBearStore(): BearState499+function useBearStore<T>(selector: (state: BearState) => T): T500+function useBearStore<T>(selector?: (state: BearState) => T) {501+ return useStore(bearStore, selector!)502+}503+```504+505+You can also make an abstract `createBoundedUseStore` function if you need to create bounded `useStore` hooks often and want to DRY things up...506+507+```ts508+import { useStore, StoreApi } from 'zustand'509+import { createStore } from 'zustand/vanilla'510+511+interface BearState {512+ bears: number513+ increase: (by: number) => void514+}515+516+const bearStore = createStore<BearState>()((set) => ({517+ bears: 0,518+ increase: (by) => set((state) => ({ bears: state.bears + by })),519+}))520+521+const createBoundedUseStore = ((store) => (selector) =>522+ useStore(store, selector)) as <S extends StoreApi<unknown>>(523+ store: S,524+) => {525+ (): ExtractState<S>526+ <T>(selector: (state: ExtractState<S>) => T): T527+}528+529+type ExtractState<S> = S extends { getState: () => infer X } ? X : never530+531+const useBearStore = createBoundedUseStore(bearStore)532+```533+534+## Middlewares and their mutators reference535+536+- `devtools` — `["zustand/devtools", never]`537+- `persist` — `["zustand/persist", YourPersistedState]`<br/>538+ `YourPersistedState` is the type of state you are going to persist, ie the return type of `options.partialize`, if you're not passing `partialize` options the `YourPersistedState` becomes `Partial<YourState>`. Also [sometimes](https://github.com/pmndrs/zustand/issues/980#issuecomment-1162289836) passing actual `PersistedState` won't work. In those cases, try passing `unknown`.539+- `immer` — `["zustand/immer", never]`540+- `subscribeWithSelector` — `["zustand/subscribeWithSelector", never]`541+- `redux` — `["zustand/redux", YourAction]`542+- `combine` — no mutator as `combine` does not mutate the storeadded:docs/learn/guides/auto-generating-selectors.md+134 added
1+---2+title: Auto Generating Selectors3+nav: 144+---5+6+We recommend using selectors when using either the properties or actions from the store. You can access values from the store like so:7+8+```typescript9+const bears = useBearStore((state) => state.bears)10+```11+12+However, writing these could be tedious. If that is the case for you, you can auto-generate your selectors.13+14+## Create the following function: `createSelectors`15+16+```typescript17+import { StoreApi, UseBoundStore } from 'zustand'18+19+type WithSelectors<S> = S extends { getState: () => infer T }20+ ? S & { use: { [K in keyof T]: () => T[K] } }21+ : never22+23+const createSelectors = <S extends UseBoundStore<StoreApi<object>>>(24+ _store: S,25+) => {26+ const store = _store as WithSelectors<typeof _store>27+ store.use = {}28+ for (const k of Object.keys(store.getState())) {29+ ;(store.use as any)[k] = () => store((s) => s[k as keyof typeof s])30+ }31+32+ return store33+}34+```35+36+If you have a store like this:37+38+```typescript39+interface BearState {40+ bears: number41+ increase: (by: number) => void42+ increment: () => void43+}44+45+const useBearStoreBase = create<BearState>()((set) => ({46+ bears: 0,47+ increase: (by) => set((state) => ({ bears: state.bears + by })),48+ increment: () => set((state) => ({ bears: state.bears + 1 })),49+}))50+```51+52+Apply that function to your store:53+54+```typescript55+const useBearStore = createSelectors(useBearStoreBase)56+```57+58+Now the selectors are auto generated and you can access them directly:59+60+```typescript61+// get the property62+const bears = useBearStore.use.bears()63+64+// get the action65+const increment = useBearStore.use.increment()66+```67+68+## Vanilla Store69+70+If you are using a vanilla store, use the following `createSelectors` function:71+72+```typescript73+import { StoreApi, useStore } from 'zustand'74+75+type WithSelectors<S> = S extends { getState: () => infer T }76+ ? S & { use: { [K in keyof T]: () => T[K] } }77+ : never78+79+const createSelectors = <S extends StoreApi<object>>(_store: S) => {80+ const store = _store as WithSelectors<typeof _store>81+ store.use = {}82+ for (const k of Object.keys(store.getState())) {83+ ;(store.use as any)[k] = () =>84+ useStore(_store, (s) => s[k as keyof typeof s])85+ }86+87+ return store88+}89+```90+91+The usage is the same as a React store. If you have a store like this:92+93+```typescript94+import { createStore } from 'zustand'95+96+interface BearState {97+ bears: number98+ increase: (by: number) => void99+ increment: () => void100+}101+102+const store = createStore<BearState>()((set) => ({103+ bears: 0,104+ increase: (by) => set((state) => ({ bears: state.bears + by })),105+ increment: () => set((state) => ({ bears: state.bears + 1 })),106+}))107+```108+109+Apply that function to your store:110+111+```typescript112+const useBearStore = createSelectors(store)113+```114+115+Now the selectors are auto generated and you can access them directly:116+117+```typescript118+// get the property119+const bears = useBearStore.use.bears()120+121+// get the action122+const increment = useBearStore.use.increment()123+```124+125+## Live Demo126+127+For a working example of this, see the [Code Sandbox](https://codesandbox.io/s/zustand-auto-generate-selectors-forked-rl8v5e?file=/src/selectors.ts).128+129+## Third-party Libraries130+131+- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook)132+- [react-hooks-global-state](https://github.com/dai-shi/react-hooks-global-state)133+- [zustood](https://github.com/udecode/zustood)134+- [@davstack/store](https://github.com/DawidWraga/davstack)added:docs/learn/guides/beginner-typescript.md+378 added
1+---2+title: Beginner TypeScript Guide3+nav: 124+---5+6+Zustand is a lightweight state manager, particularly used with React. Zustand avoids reducers, context, and boilerplate.7+Paired with TypeScript, you get a strongly typed store-state, actions, and selectors-with autocomplete and compile-time safety.8+9+In this basic guide we’ll cover:10+11+- Creating a typed store (state + actions)12+- Using the store in React components with type safety13+- Resetting the store safely with types14+- Extracting and reusing Store type (for props, tests, and utilities)15+- Composing multiple selectors and building derived state (with type inference and without extra re-renders)16+- Middlewares with TypeScript support (`combine`, `devtools`, `persist`)17+- Async actions with typed API responses18+- Working with `createWithEqualityFn` (enhanced `create` store function)19+- Structuring and coordinating multiple stores20+21+### Creating a Store with State & Actions22+23+Here we describe state and actions using an Typescript interface. The `<BearState>` generic forces the store to match this shape.24+This means if you forget a field or use the wrong type, TypeScript will complain. Unlike plain JS, this guarantees type-safe state management.25+The `create` function uses the curried form, which results in a store of type `UseBoundStore<StoreApi<BearState>>`.26+27+```ts28+// store.ts29+import { create } from 'zustand'30+31+// Define types for state & actions32+interface BearState {33+ bears: number34+ food: string35+ feed: (food: string) => void36+}37+38+// Create store using the curried form of `create`39+export const useBearStore = create<BearState>()((set) => ({40+ bears: 2,41+ food: 'honey',42+ feed: (food) => set(() => ({ food })),43+}))44+```45+46+### Using the Store in Components47+48+Inside components, you can read state and call actions. Selectors `(s) => s.bears` subscribe to only what you need.49+This reduces re-renders and improves performance. JS can do this too, but with TS your IDE autocompletes state fields.50+51+```tsx52+import { useBearStore } from './store'53+54+function BearCounter() {55+ // Select only 'bears' to avoid unnecessary re-renders56+ const bears = useBearStore((s) => s.bears)57+ return <h1>{bears} bears around</h1>58+}59+```60+61+### Resetting the Store62+63+Resetting is useful after logout or “clear session”. We use `typeof initialState` to avoid repeating property types.64+TypeScript updates automatically if `initialState` changes. This is safer and cleaner compared to JS.65+66+```tsx67+import { create } from 'zustand'68+69+const initialState = { bears: 0, food: 'honey' }70+71+// Reuse state type dynamically72+type BearState = typeof initialState & {73+ increase: (by: number) => void74+ reset: () => void75+}76+77+const useBearStore = create<BearState>()((set) => ({78+ ...initialState,79+ increase: (by) => set((s) => ({ bears: s.bears + by })),80+ reset: () => set(initialState),81+}))82+83+function ResetZoo() {84+ const { bears, increase, reset } = useBearStore()85+86+ return (87+ <div>88+ <div>{bears}</div>89+ <button onClick={() => increase(5)}>Increase by 5</button>90+ <button onClick={reset}>Reset</button>91+ </div>92+ )93+}94+```95+96+### Extracting Types97+98+Zustand provides a built-in helper called `ExtractState`. This is useful for tests, utility functions, or component props.99+It returns the full type of your store’s state and actions without having to manually redefine them. Extracting the Store type:100+101+```ts102+// store.ts103+import { create, type ExtractState } from 'zustand'104+105+export const useBearStore = create((set) => ({106+ bears: 3,107+ food: 'honey',108+ increase: (by: number) => set((s) => ({ bears: s.bears + by })),109+}))110+111+// Extract the type of the whole store state112+export type BearState = ExtractState<typeof useBearStore>113+```114+115+Using extracted type in tests:116+117+```ts118+// test.cy.ts119+import { BearState } from './store.ts'120+121+test('should reset store', () => {122+ const snapshot: BearState = useBearStore.getState()123+ expect(snapshot.bears).toBeGreaterThanOrEqual(0)124+})125+```126+127+and in utility function:128+129+```ts130+// util.ts131+import { BearState } from './store.ts'132+133+function logBearState(state: BearState) {134+ console.log(`We have ${state.bears} bears eating ${state.food}`)135+}136+137+logBearState(useBearStore.getState())138+```139+140+### Selectors141+142+#### Multiple Selectors143+144+Sometimes you need more than one property. Returning an object from the selector lets you access multiple fields at once.145+However, directly destructuring properties from that object can cause unnecessary re-renders.146+To avoid this, it’s recommended to wrap the selector with `useShallow`, which prevents re-renders when the selected values remain shallowly equal.147+This is more efficient than subscribing to the whole store. TypeScript ensures you can’t accidentally misspell `bears` or `food`.148+See the [API documentation](https://zustand.docs.pmnd.rs/hooks/use-shallow) for more details on `useShallow`.149+150+```tsx151+import { create } from 'zustand'152+import { useShallow } from 'zustand/react/shallow'153+154+// Bear store with explicit types155+interface BearState {156+ bears: number157+ food: number158+}159+160+const useBearStore = create<BearState>()(() => ({161+ bears: 2,162+ food: 10,163+}))164+165+// In components, you can use both stores safely166+function MultipleSelectors() {167+ const { bears, food } = useBearStore(168+ useShallow((state) => ({ bears: state.bears, food: state.food })),169+ )170+171+ return (172+ <div>173+ We have {food} units of food for {bears} bears174+ </div>175+ )176+}177+```178+179+#### Derived State with Selectors180+181+Not all values need to be stored directly - some can be computed from existing state. You can derive values using selectors.182+This avoids duplication and keeps the store minimal. TypeScript ensures `bears` is a number, so math is safe.183+184+```tsx185+import { create } from 'zustand'186+187+interface BearState {188+ bears: number189+ foodPerBear: number190+}191+192+const useBearStore = create<BearState>()(() => ({193+ bears: 3,194+ foodPerBear: 2,195+}))196+197+function TotalFood() {198+ // Derived value: required amount food for all bears199+ const totalFood = useBearStore((s) => s.bears * s.foodPerBear) // don't need to have extra property `{ totalFood: 6 }` in your Store200+201+ return <div>We need ${totalFood} jars of honey</div>202+}203+```204+205+### Middlewares206+207+#### `combine` middleware208+209+This middleware separates initial state and actions, making the code cleaner.210+TS automatically infers types from the state and actions, no interface needed.211+This is different from JS, where type safety is missing. It’s a very popular style in TypeScript projects.212+See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/combine) for more details.213+214+```ts215+import { create } from 'zustand'216+import { combine } from 'zustand/middleware'217+218+interface BearState {219+ bears: number220+ increase: () => void221+}222+223+// State + actions are separated224+export const useBearStore = create<BearState>()(225+ combine({ bears: 0 }, (set) => ({226+ increase: () => set((s) => ({ bears: s.bears + 1 })),227+ })),228+)229+```230+231+#### `devtools` middleware232+233+This middleware connects Zustand to Redux DevTools. You can inspect changes, time-travel, and debug state.234+It’s extremely useful in development. TS ensures your actions and state remain type-checked even here.235+See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/devtools) for more details.236+237+```ts238+import { create } from 'zustand'239+import { devtools } from 'zustand/middleware'240+241+interface BearState {242+ bears: number243+ increase: () => void244+}245+246+export const useBearStore = create<BearState>()(247+ devtools((set) => ({248+ bears: 0,249+ increase: () => set((s) => ({ bears: s.bears + 1 })),250+ })),251+)252+```253+254+#### `persist` middleware255+256+This middleware keeps your store in `localStorage` (or another storage). This means your bears survive a page refresh.257+Great for apps where persistence matters. In TS, the state type stays consistent, so no runtime surprises.258+See the [API documentation](https://zustand.docs.pmnd.rs/middlewares/persist) for more details.259+260+```ts261+import { create } from 'zustand'262+import { persist } from 'zustand/middleware'263+264+interface BearState {265+ bears: number266+ increase: () => void267+}268+269+export const useBearStore = create<BearState>()(270+ persist(271+ (set) => ({272+ bears: 0,273+ increase: () => set((s) => ({ bears: s.bears + 1 })),274+ }),275+ { name: 'bear-storage' }, // localStorage key276+ ),277+)278+```279+280+### Async Actions281+282+Actions can be async to fetch remote data. Here we fetch bears count and update state.283+TS enforces correct API response type (`BearData`). In JS you might misspell `count` - TS prevents that.284+285+```ts286+import { create } from 'zustand'287+288+interface BearData {289+ count: number290+}291+292+interface BearState {293+ bears: number294+ fetchBears: () => Promise<void>295+}296+297+export const useBearStore = create<BearState>()((set) => ({298+ bears: 0,299+ fetchBears: async () => {300+ const res = await fetch('/api/bears')301+ const data: BearData = await res.json()302+303+ set({ bears: data.count })304+ },305+}))306+```307+308+### `createWithEqualityFn`309+310+Variant of `create` with equality built-in. Useful if you always want custom equality checks.311+Not common, but shows Zustand’s flexibility. TS still keeps full type inference.312+See the [API documentation](https://zustand.docs.pmnd.rs/apis/create-with-equality-fn) for more details.313+314+```ts315+import { createWithEqualityFn } from 'zustand/traditional'316+import { shallow } from 'zustand/shallow'317+318+const useBearStore = createWithEqualityFn(() => ({319+ bears: 0,320+}))321+322+const bears = useBearStore((s) => s.bears, Object.is)323+// or324+const bears = useBearStore((s) => ({ bears: s.bears }), shallow)325+```326+327+### Multiple Stores328+329+You can create more than one store for different domains. For example, `BearStore` manages bears and `FishStore` manages fish.330+This keeps state isolated and easier to maintain in larger apps. With TypeScript, each store has its own strict type - you can’t accidentally mix bears and fish.331+332+```tsx333+import { create } from 'zustand'334+335+// Bear store with explicit types336+interface BearState {337+ bears: number338+ addBear: () => void339+}340+341+const useBearStore = create<BearState>()((set) => ({342+ bears: 2,343+ addBear: () => set((s) => ({ bears: s.bears + 1 })),344+}))345+346+// Fish store with explicit types347+interface FishState {348+ fish: number349+ addFish: () => void350+}351+352+const useFishStore = create<FishState>()((set) => ({353+ fish: 5,354+ addFish: () => set((s) => ({ fish: s.fish + 1 })),355+}))356+357+// In components, you can use both stores safely358+function Zoo() {359+ const { bears, addBear } = useBearStore()360+ const { fish, addFish } = useFishStore()361+362+ return (363+ <div>364+ <div>365+ {bears} bears and {fish} fish366+ </div>367+ <button onClick={addBear}>Add bear</button>368+ <button onClick={addFish}>Add fish</button>369+ </div>370+ )371+}372+```373+374+### Conclusion375+376+Zustand together with TypeScript provides a balance: you keep the simplicity of small, minimalistic stores, while gaining the safety of strong typing.377+You don’t need boilerplate or complex patterns - state and actions live side by side, fully typed, and ready to use.378+Start with a basic store to learn the pattern, then expand gradually: use `combine` for cleaner inference, `persist` for storage, and `devtools` for debugging.added:docs/learn/guides/connect-to-state-with-url-hash.md+153 added
1+---2+title: Connect to state with URL3+nav: 104+---5+6+## Connect State with URL Hash7+8+If you want to connect state of a store to URL hash, you can create your own hash storage.9+10+```ts11+import { create } from 'zustand'12+import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'13+14+const hashStorage: StateStorage = {15+ getItem: (key): string => {16+ const searchParams = new URLSearchParams(location.hash.slice(1))17+ const storedValue = searchParams.get(key) ?? ''18+ return JSON.parse(storedValue)19+ },20+ setItem: (key, newValue): void => {21+ const searchParams = new URLSearchParams(location.hash.slice(1))22+ searchParams.set(key, JSON.stringify(newValue))23+ location.hash = searchParams.toString()24+ },25+ removeItem: (key): void => {26+ const searchParams = new URLSearchParams(location.hash.slice(1))27+ searchParams.delete(key)28+ location.hash = searchParams.toString()29+ },30+}31+32+export const useBoundStore = create()(33+ persist(34+ (set, get) => ({35+ fishes: 0,36+ addAFish: () => set({ fishes: get().fishes + 1 }),37+ }),38+ {39+ name: 'food-storage', // unique name40+ storage: createJSONStorage(() => hashStorage),41+ },42+ ),43+)44+```45+46+## Persist and Connect State with URL Parameters (Example: URL Query Parameters)47+48+There are times when you want to conditionally connect the state to the URL.49+This example depicts usage of the URL query parameters50+while keeping it synced with another persistence implementation, like `localstorage`.51+52+If you want the URL params to always populate, the conditional check on `getUrlSearch()` can be removed.53+54+The implementation below will update the URL in place, without refresh, as the relevant states change.55+56+```ts57+import { create } from 'zustand'58+import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'59+60+const getUrlSearch = () => {61+ return window.location.search.slice(1)62+}63+64+const persistentStorage: StateStorage = {65+ getItem: (key): string => {66+ // Check URL first67+ if (getUrlSearch()) {68+ const searchParams = new URLSearchParams(getUrlSearch())69+ const storedValue = searchParams.get(key)70+ return JSON.parse(storedValue as string)71+ } else {72+ // Otherwise, we should load from localstorage or alternative storage73+ return JSON.parse(localStorage.getItem(key) as string)74+ }75+ },76+ setItem: (key, newValue): void => {77+ // Check if query params exist at all, can remove check if always want to set URL78+ if (getUrlSearch()) {79+ const searchParams = new URLSearchParams(getUrlSearch())80+ searchParams.set(key, JSON.stringify(newValue))81+ window.history.replaceState(null, '', `?${searchParams.toString()}`)82+ }83+84+ localStorage.setItem(key, JSON.stringify(newValue))85+ },86+ removeItem: (key): void => {87+ const searchParams = new URLSearchParams(getUrlSearch())88+ searchParams.delete(key)89+ window.location.search = searchParams.toString()90+ },91+}92+93+type LocalAndUrlStore = {94+ typesOfFish: string[]95+ addTypeOfFish: (fishType: string) => void96+ numberOfBears: number97+ setNumberOfBears: (newNumber: number) => void98+}99+100+const storageOptions = {101+ name: 'fishAndBearsStore',102+ storage: createJSONStorage<LocalAndUrlStore>(() => persistentStorage),103+}104+105+const useLocalAndUrlStore = create()(106+ persist<LocalAndUrlStore>(107+ (set) => ({108+ typesOfFish: [],109+ addTypeOfFish: (fishType) =>110+ set((state) => ({ typesOfFish: [...state.typesOfFish, fishType] })),111+112+ numberOfBears: 0,113+ setNumberOfBears: (numberOfBears) => set(() => ({ numberOfBears })),114+ }),115+ storageOptions,116+ ),117+)118+119+export default useLocalAndUrlStore120+```121+122+When generating the URL from a component, you can call buildShareableUrl:123+124+```ts125+const buildURLSuffix = (params, version = 0) => {126+ const searchParams = new URLSearchParams()127+128+ const zustandStoreParams = {129+ state: {130+ typesOfFish: params.typesOfFish,131+ numberOfBears: params.numberOfBears,132+ },133+ version: version, // version is here because that is included with how Zustand sets the state134+ }135+136+ // The URL param key should match the name of the store, as specified as in storageOptions above137+ searchParams.set('fishAndBearsStore', JSON.stringify(zustandStoreParams))138+ return searchParams.toString()139+}140+141+export const buildShareableUrl = (params, version) => {142+ return `${window.location.origin}?${buildURLSuffix(params, version)}`143+}144+```145+146+The generated URL would look like (here without any encoding, for readability):147+148+`https://localhost/search?fishAndBearsStore={"state":{"typesOfFish":["tilapia","salmon"],"numberOfBears":15},"version":0}}`149+150+### Demo151+152+- Hash: https://stackblitz.com/edit/vitejs-vite-9vg24prg153+- Query: https://stackblitz.com/edit/vitejs-vite-hyc97ynfadded:docs/learn/guides/event-handler-in-pre-react-18.md+24 added
1+---2+title: Calling actions outside a React event handler in pre React 183+nav: 114+---5+6+Because React handles `setState` synchronously if it's called outside an event handler, updating the state outside an event handler will force react to update the components synchronously. Therefore, there is a risk of encountering the zombie-child effect.7+In order to fix this, the action needs to be wrapped in `unstable_batchedUpdates` like so:8+9+```jsx10+import { unstable_batchedUpdates } from 'react-dom' // or 'react-native'11+12+const useFishStore = create((set) => ({13+ fishes: 0,14+ increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 })),15+}))16+17+const nonReactCallback = () => {18+ unstable_batchedUpdates(() => {19+ useFishStore.getState().increaseFishes()20+ })21+}22+```23+24+More details: https://github.com/pmndrs/zustand/issues/302added:docs/learn/guides/flux-inspired-practice.md+77 added
1+---2+title: Flux inspired practice3+nav: 194+---5+6+Although Zustand is an unopinionated library, we do recommend a few patterns.7+These are inspired by practices originally found in [Flux](https://github.com/facebookarchive/flux),8+and more recently [Redux](https://redux.js.org/understanding/thinking-in-redux/three-principles),9+so if you are coming from another library, you should feel right at home.10+11+However, Zustand does differ in some fundamental ways,12+so some terminology may not perfectly align to other libraries.13+14+## Recommended patterns15+16+### Single store17+18+Your applications global state should be located in a single Zustand store.19+20+If you have a large application, Zustand supports [splitting the store into slices](./slices-pattern.md).21+22+### Use `set` / `setState` to update the store23+24+Always use `set` (or `setState`) to perform updates to your store.25+`set` (and `setState`) ensures the described update is correctly merged and listeners are appropriately notified.26+27+### Colocate store actions28+29+In Zustand, state can be updated without the use of dispatched actions and reducers found in other Flux libraries.30+These store actions can be added directly to the store as shown below.31+32+Optionally, by using `setState` they can be [located external to the store](./practice-with-no-store-actions.md)33+34+```js35+const useBoundStore = create((set) => ({36+ storeSliceA: ...,37+ storeSliceB: ...,38+ storeSliceC: ...,39+ updateX: () => set(...),40+ updateY: () => set(...),41+}))42+```43+44+## Redux-like patterns45+46+If you can't live without Redux-like reducers, you can define a `dispatch` function on the root level of the store:47+48+```typescript49+const types = { increase: 'INCREASE', decrease: 'DECREASE' }50+51+const reducer = (state, { type, by = 1 }) => {52+ switch (type) {53+ case types.increase:54+ return { grumpiness: state.grumpiness + by }55+ case types.decrease:56+ return { grumpiness: state.grumpiness - by }57+ }58+}59+60+const useGrumpyStore = create((set) => ({61+ grumpiness: 0,62+ dispatch: (args) => set((state) => reducer(state, args)),63+}))64+65+const dispatch = useGrumpyStore((state) => state.dispatch)66+dispatch({ type: types.increase, by: 2 })67+```68+69+You could also use our redux-middleware. It wires up your main reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api.70+71+```typescript72+import { redux } from 'zustand/middleware'73+74+const useReduxStore = create(redux(reducer, initialState))75+```76+77+Another way to update the store could be through functions wrapping the state functions. These could also handle side-effects of actions. For example, with HTTP-calls. To use Zustand in a non-reactive way, see [the readme](https://github.com/pmndrs/zustand#readingwriting-state-and-reacting-to-changes-outside-of-components).added:docs/learn/guides/how-to-reset-state.md+45 added
1+---2+title: How to reset state3+nav: 204+---5+6+The following pattern can be used to reset the state to its initial value.7+8+```ts9+const useSomeStore = create<State & Actions>()((set, get, store) => ({10+ // your code here11+ reset: () => {12+ set(store.getInitialState())13+ },14+}))15+```16+17+Resetting multiple stores at once18+19+```ts20+import type { StateCreator } from 'zustand'21+import { create: actualCreate } from 'zustand'22+23+const storeResetFns = new Set<() => void>()24+25+const resetAllStores = () => {26+ storeResetFns.forEach((resetFn) => {27+ resetFn()28+ })29+}30+31+export const create = (<T>() => {32+ return (stateCreator: StateCreator<T>) => {33+ const store = actualCreate(stateCreator)34+ storeResetFns.add(() => {35+ store.setState(store.getInitialState(), true)36+ })37+ return store38+ }39+}) as typeof actualCreate40+```41+42+## Demo43+44+- Basic: https://stackblitz.com/edit/zustand-how-to-reset-state-basic45+- Advanced: https://stackblitz.com/edit/zustand-how-to-reset-state-advancedadded:docs/learn/guides/immutable-state-and-merging.md+59 added
1+---2+title: Immutable state and merging3+nav: 74+---5+6+Like with React's `useState`, we need to update state immutably.7+8+Here's a typical example:9+10+```jsx11+import { create } from 'zustand'12+13+const useCountStore = create((set) => ({14+ count: 0,15+ inc: () => set((state) => ({ count: state.count + 1 })),16+}))17+```18+19+The `set` function is to update state in the store.20+Because the state is immutable, it should have been like this:21+22+```js23+set((state) => ({ ...state, count: state.count + 1 }))24+```25+26+However, as this is a common pattern, `set` actually merges state, and27+we can skip the `...state` part:28+29+```js30+set((state) => ({ count: state.count + 1 }))31+```32+33+## Nested objects34+35+The `set` function merges state at only one level.36+If you have a nested object, you need to merge them explicitly. You will use the spread operator pattern like so:37+38+```jsx39+import { create } from 'zustand'40+41+const useCountStore = create((set) => ({42+ nested: { count: 0 },43+ inc: () =>44+ set((state) => ({45+ nested: { ...state.nested, count: state.nested.count + 1 },46+ })),47+}))48+```49+50+For complex use cases, consider using some libraries that help with immutable updates.51+You can refer to [Updating nested state object values](./updating-state.md#deeply-nested-object).52+53+## Replace flag54+55+To disable the merging behavior, you can specify a `replace` boolean value for `set` like so:56+57+```js58+set((state) => newState, true)59+```added:docs/learn/guides/initialize-state-with-props.md+180 added
1+---2+title: Initialize state with props3+nav: 174+---5+6+In cases where [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) is needed, such as when a store should be initialized with props from a component, the recommended approach is to use a vanilla store with React.context.7+8+## Store creator with `createStore`9+10+```ts11+import { createStore } from 'zustand'12+13+interface BearProps {14+ bears: number15+}16+17+interface BearState extends BearProps {18+ addBear: () => void19+}20+21+type BearStore = ReturnType<typeof createBearStore>22+23+const createBearStore = (initProps?: Partial<BearProps>) => {24+ const DEFAULT_PROPS: BearProps = {25+ bears: 0,26+ }27+ return createStore<BearState>()((set) => ({28+ ...DEFAULT_PROPS,29+ ...initProps,30+ addBear: () => set((state) => ({ bears: ++state.bears })),31+ }))32+}33+```34+35+## Creating a context with `React.createContext`36+37+```ts38+import { createContext } from 'react'39+40+export const BearContext = createContext<BearStore | null>(null)41+```42+43+## Basic component usage44+45+```tsx46+// Provider implementation47+import { useState } from 'react'48+49+function App() {50+ const [store] = useState(() => createBearStore())51+ return (52+ <BearContext.Provider value={store}>53+ <BasicConsumer />54+ </BearContext.Provider>55+ )56+}57+```58+59+```tsx60+// Consumer component61+import { useContext } from 'react'62+import { useStore } from 'zustand'63+64+function BasicConsumer() {65+ const store = useContext(BearContext)66+ if (!store) throw new Error('Missing BearContext.Provider in the tree')67+68+ const bears = useStore(store, (s) => s.bears)69+ const addBear = useStore(store, (s) => s.addBear)70+71+ return (72+ <>73+ <div>{bears} Bears.</div>74+ <button onClick={addBear}>Add bear</button>75+ </>76+ )77+}78+```79+80+## Common patterns81+82+### Wrapping the context provider83+84+```tsx85+// Provider wrapper86+import { useState } from 'react'87+88+type BearProviderProps = React.PropsWithChildren<BearProps>89+90+function BearProvider({ children, ...props }: BearProviderProps) {91+ const [store] = useState(() => createBearStore(props))92+ return <BearContext.Provider value={store}>{children}</BearContext.Provider>93+}94+```95+96+### Extracting context logic into a custom hook97+98+```tsx99+// Mimic the hook returned by `create`100+import { useContext } from 'react'101+import { useStore } from 'zustand'102+103+function useBearContext<T>(selector: (state: BearState) => T): T {104+ const store = useContext(BearContext)105+ if (!store) throw new Error('Missing BearContext.Provider in the tree')106+ return useStore(store, selector)107+}108+```109+110+```tsx111+// Consumer usage of the custom hook112+function CommonConsumer() {113+ const bears = useBearContext((s) => s.bears)114+ const addBear = useBearContext((s) => s.addBear)115+ return (116+ <>117+ <div>{bears} Bears.</div>118+ <button onClick={addBear}>Add bear</button>119+ </>120+ )121+}122+```123+124+### Optionally use memoized selector for stable outputs125+126+```tsx127+import { useShallow } from 'zustand/react/shallow'128+129+const meals = ['Salmon', 'Berries', 'Nuts']130+131+function CommonConsumer() {132+ const bearMealsOrder = useBearContext(133+ useShallow((s) =>134+ Array.from({ length: s.bears }).map((_, index) =>135+ meals.at(index % meals.length),136+ ),137+ ),138+ )139+ return (140+ <>141+ Order:142+ <ul>143+ {bearMealsOrder.map((meal) => (144+ <li key={meal}>{meal}</li>145+ ))}146+ </ul>147+ </>148+ )149+}150+```151+152+### Optionally allow using a custom equality function153+154+```tsx155+// Allow custom equality function by using useStoreWithEqualityFn instead of useStore156+import { useContext } from 'react'157+import { useStoreWithEqualityFn } from 'zustand/traditional'158+159+function useBearContext<T>(160+ selector: (state: BearState) => T,161+ equalityFn?: (left: T, right: T) => boolean,162+): T {163+ const store = useContext(BearContext)164+ if (!store) throw new Error('Missing BearContext.Provider in the tree')165+ return useStoreWithEqualityFn(store, selector, equalityFn)166+}167+```168+169+### Complete example170+171+```tsx172+// Provider wrapper & custom hook consumer173+function App2() {174+ return (175+ <BearProvider bears={2}>176+ <HookConsumer />177+ </BearProvider>178+ )179+}180+```added:docs/learn/guides/maps-and-sets-usage.md+115 added
1+---2+title: Map and Set Usage3+nav: 84+---5+6+# Map and Set in Zustand7+8+Map and Set are mutable data structures. To use them in Zustand, you must create new instances when updating.9+10+## Map11+12+### Reading a Map13+14+```typescript15+const foo = useSomeStore((state) => state.foo)16+```17+18+### Updating a Map19+20+Always create a new Map instance:21+22+```ts23+// Update single entry24+set((state) => ({25+ foo: new Map(state.foo).set(key, value),26+}))27+28+// Delete entry29+set((state) => {30+ const next = new Map(state.foo)31+ next.delete(key)32+ return { foo: next }33+})34+35+// Update multiple entries36+set((state) => {37+ const next = new Map(state.foo)38+ next.set('key1', 'value1')39+ next.set('key2', 'value2')40+ return { foo: next }41+})42+43+// Clear44+set({ foo: new Map() })45+```46+47+## Set48+49+### Reading a Set50+51+```ts52+const bar = useSomeStore((state) => state.bar)53+```54+55+### Updating a Set56+57+Always create a new Set instance:58+59+```ts60+// Add item61+set((state) => ({62+ bar: new Set(state.bar).add(item),63+}))64+65+// Delete item66+set((state) => {67+ const next = new Set(state.bar)68+ next.delete(item)69+ return { bar: next }70+})71+72+// Toggle item73+set((state) => {74+ const next = new Set(state.bar)75+ next.has(item) ? next.delete(item) : next.add(item)76+ return { bar: next }77+})78+79+// Clear80+set({ bar: new Set() })81+```82+83+## Why New Instances?84+85+Zustand detects changes by comparing references. Mutating a Map or Set doesn't change its reference:86+87+```ts88+// ❌ Wrong - same reference, no re-render89+set((state) => {90+ state.foo.set(key, value)91+ return { foo: state.foo }92+})93+94+// ✅ Correct - new reference, triggers re-render95+set((state) => ({96+ foo: new Map(state.foo).set(key, value),97+}))98+```99+100+## Pitfall: Type Hints for Empty Collections101+102+Provide type hints when initializing empty Maps and Sets:103+104+```ts105+{106+ ids: new Set([] as string[]),107+ users: new Map([] as [string, User][])108+}109+```110+111+Without type hints, TypeScript infers `never[]` which prevents adding items later.112+113+## Demos114+115+Basic: https://stackblitz.com/edit/vitejs-vite-5cu5ddvxadded:docs/learn/guides/nextjs.md+316 added
1+---2+title: Setup with Next.js3+nav: 154+---5+6+> [!NOTE]7+> We will be updating this guide soon based on our discussion in https://github.com/pmndrs/zustand/discussions/2740.8+9+[Next.js](https://nextjs.org) is a popular server-side rendering framework for React that presents10+some unique challenges for using Zustand properly.11+Keep in mind that Zustand store is a global12+variable (AKA module state) making it optional to use a `Context`.13+These challenges include:14+15+- **Per-request store:** A Next.js server can handle multiple requests simultaneously. This means16+ that the store should be created per request and should not be shared across requests.17+- **SSR friendly:** Next.js applications are rendered twice, first on the server18+ and again on the client. Having different outputs on both the client and the server will result19+ in "hydration errors." The store will have to be initialized on the server and then20+ re-initialized on the client with the same data in order to avoid that. Please read more about21+ that in our [SSR and Hydration](./ssr-and-hydration.md) guide.22+- **SPA routing friendly:** Next.js supports a hybrid model for client side routing, which means23+ that in order to reset a store, we need to initialize it at the component level using a24+ `Context`.25+- **Server caching friendly:** Recent versions of Next.js (specifically applications using the App26+ Router architecture) support aggressive server caching. Due to our store being a **module state**,27+ it is completely compatible with this caching.28+29+We have these general recommendations for the appropriate use of Zustand:30+31+- **No global stores** - Because the store should not be shared across requests, it should not be defined32+ as a global variable. Instead, the store should be created per request.33+- **React Server Components should not read from or write to the store** - RSCs cannot use hooks or context. They aren't34+ meant to be stateful. Having an RSC read from or write values to a global store violates the35+ architecture of Next.js.36+37+### Creating a store per request38+39+Let's write our store factory function that will create a new store for each40+request.41+42+```json43+// tsconfig.json44+{45+ "compilerOptions": {46+ "lib": ["dom", "dom.iterable", "esnext"],47+ "allowJs": true,48+ "skipLibCheck": true,49+ "strict": true,50+ "noEmit": true,51+ "esModuleInterop": true,52+ "module": "esnext",53+ "moduleResolution": "bundler",54+ "resolveJsonModule": true,55+ "isolatedModules": true,56+ "jsx": "preserve",57+ "incremental": true,58+ "plugins": [59+ {60+ "name": "next"61+ }62+ ],63+ "paths": {64+ "@/*": ["./src/*"]65+ }66+ },67+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],68+ "exclude": ["node_modules"]69+}70+```71+72+> **Note:** do not forget to remove all comments from your `tsconfig.json` file.73+74+### Initializing the store75+76+```ts77+// src/stores/counter-store.ts78+import { createStore } from 'zustand/vanilla'79+80+export type CounterState = {81+ count: number82+}83+84+export type CounterActions = {85+ decrementCount: () => void86+ incrementCount: () => void87+}88+89+export type CounterStore = CounterState & CounterActions90+91+export const defaultInitState: CounterState = {92+ count: 0,93+}94+95+export const createCounterStore = (96+ initState: CounterState = defaultInitState,97+) => {98+ return createStore<CounterStore>()((set) => ({99+ ...initState,100+ decrementCount: () => set((state) => ({ count: state.count - 1 })),101+ incrementCount: () => set((state) => ({ count: state.count + 1 })),102+ }))103+}104+```105+106+### Providing the store107+108+Let's use the `createCounterStore` in our component and share it using a context provider.109+110+```tsx111+// src/providers/counter-store-provider.tsx112+'use client'113+114+import { type ReactNode, createContext, useState, useContext } from 'react'115+import { useStore } from 'zustand'116+117+import { type CounterStore, createCounterStore } from '@/stores/counter-store'118+119+export type CounterStoreApi = ReturnType<typeof createCounterStore>120+121+export const CounterStoreContext = createContext<CounterStoreApi | undefined>(122+ undefined,123+)124+125+export interface CounterStoreProviderProps {126+ children: ReactNode127+}128+129+export const CounterStoreProvider = ({130+ children,131+}: CounterStoreProviderProps) => {132+ const [store] = useState(() => createCounterStore())133+ return (134+ <CounterStoreContext.Provider value={store}>135+ {children}136+ </CounterStoreContext.Provider>137+ )138+}139+140+export const useCounterStore = <T,>(141+ selector: (store: CounterStore) => T,142+): T => {143+ const counterStoreContext = useContext(CounterStoreContext)144+ if (!counterStoreContext) {145+ throw new Error(`useCounterStore must be used within CounterStoreProvider`)146+ }147+148+ return useStore(counterStoreContext, selector)149+}150+```151+152+> **Note:** In this example, we ensure that this component is re-render-safe by checking the153+> value of the reference, so that the store is only created once. This component will only be154+> rendered once per request on the server, but might be re-rendered multiple times on the client if155+> there are stateful client components located above this component in the tree, or if this component156+> also contains other mutable state that causes a re-render.157+158+### Using the store with different architectures159+160+There are two architectures for a Next.js application: the161+[Pages Router](https://nextjs.org/docs/pages/building-your-application/routing) and the162+[App Router](https://nextjs.org/docs/app/building-your-application/routing). The usage of Zustand on163+both architectures should be the same with slight differences related to each architecture.164+165+#### Pages Router166+167+```tsx168+// src/components/pages/home-page.tsx169+import { useCounterStore } from '@/providers/counter-store-provider'170+171+export const HomePage = () => {172+ const { count, incrementCount, decrementCount } = useCounterStore(173+ (state) => state,174+ )175+176+ return (177+ <div>178+ Count: {count}179+ <hr />180+ <button type="button" onClick={incrementCount}>181+ Increment Count182+ </button>183+ <button type="button" onClick={decrementCount}>184+ Decrement Count185+ </button>186+ </div>187+ )188+}189+```190+191+```tsx192+// src/_app.tsx193+import type { AppProps } from 'next/app'194+195+import { CounterStoreProvider } from '@/providers/counter-store-provider'196+197+export default function App({ Component, pageProps }: AppProps) {198+ return (199+ <CounterStoreProvider>200+ <Component {...pageProps} />201+ </CounterStoreProvider>202+ )203+}204+```205+206+```tsx207+// src/pages/index.tsx208+import { HomePage } from '@/components/pages/home-page'209+210+export default function Home() {211+ return <HomePage />212+}213+```214+215+> **Note:** creating a store per route would require creating and sharing the store216+> at page (route) component level. Try not to use this if you do not need to create217+> a store per route.218+219+```tsx220+// src/pages/index.tsx221+import { CounterStoreProvider } from '@/providers/counter-store-provider'222+import { HomePage } from '@/components/pages/home-page'223+224+export default function Home() {225+ return (226+ <CounterStoreProvider>227+ <HomePage />228+ </CounterStoreProvider>229+ )230+}231+```232+233+#### App Router234+235+```tsx236+// src/components/pages/home-page.tsx237+'use client'238+239+import { useCounterStore } from '@/providers/counter-store-provider'240+241+export const HomePage = () => {242+ const { count, incrementCount, decrementCount } = useCounterStore(243+ (state) => state,244+ )245+246+ return (247+ <div>248+ Count: {count}249+ <hr />250+ <button type="button" onClick={incrementCount}>251+ Increment Count252+ </button>253+ <button type="button" onClick={decrementCount}>254+ Decrement Count255+ </button>256+ </div>257+ )258+}259+```260+261+```tsx262+// src/app/layout.tsx263+import type { Metadata } from 'next'264+import { Inter } from 'next/font/google'265+import './globals.css'266+267+import { CounterStoreProvider } from '@/providers/counter-store-provider'268+269+const inter = Inter({ subsets: ['latin'] })270+271+export const metadata: Metadata = {272+ title: 'Create Next App',273+ description: 'Generated by create next app',274+}275+276+export default function RootLayout({277+ children,278+}: Readonly<{279+ children: React.ReactNode280+}>) {281+ return (282+ <html lang="en">283+ <body className={inter.className}>284+ <CounterStoreProvider>{children}</CounterStoreProvider>285+ </body>286+ </html>287+ )288+}289+```290+291+```tsx292+// src/app/page.tsx293+import { HomePage } from '@/components/pages/home-page'294+295+export default function Home() {296+ return <HomePage />297+}298+```299+300+> **Note:** creating a store per route would require creating and sharing the store301+> at page (route) component level. Try not to use this if you do not need to create302+> a store per route.303+304+```tsx305+// src/app/page.tsx306+import { CounterStoreProvider } from '@/providers/counter-store-provider'307+import { HomePage } from '@/components/pages/home-page'308+309+export default function Home() {310+ return (311+ <CounterStoreProvider>312+ <HomePage />313+ </CounterStoreProvider>314+ )315+}316+```added:docs/learn/guides/practice-with-no-store-actions.md+42 added
1+---2+title: Practice with no store actions3+nav: 54+---5+6+The recommended usage is to colocate actions and states within the store (let your actions be located together with your state).7+8+For example:9+10+```js11+export const useBoundStore = create((set) => ({12+ count: 0,13+ text: 'hello',14+ inc: () => set((state) => ({ count: state.count + 1 })),15+ setText: (text) => set({ text }),16+}))17+```18+19+This creates a self-contained store with data and actions together.20+21+---22+23+An alternative approach is to define actions at module level, external to the store.24+25+```js26+export const useBoundStore = create(() => ({27+ count: 0,28+ text: 'hello',29+}))30+31+export const inc = () =>32+ useBoundStore.setState((state) => ({ count: state.count + 1 }))33+34+export const setText = (text) => useBoundStore.setState({ text })35+```36+37+This has a few advantages:38+39+- It doesn't require a hook to call an action;40+- It facilitates code splitting.41+42+While this pattern doesn't offer any downsides, some may prefer colocating due to its encapsulated nature.added:docs/learn/guides/prevent-rerenders-with-use-shallow.md+63 added
1+---2+title: Prevent rerenders with useShallow3+nav: 94+---5+6+When you need to subscribe to a computed state from a store, the recommended way is to7+use a selector.8+9+The computed selector will cause a rerender if the output has changed according to [Object.is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is?retiredLocale=it).10+11+In this case you might want to use `useShallow` to avoid a rerender if the computed value is always shallow12+equal the previous one.13+14+## Example15+16+We have a store that associates to each bear a meal and we want to render their names.17+18+```js19+import { create } from 'zustand'20+21+const useMeals = create(() => ({22+ papaBear: 'large porridge-pot',23+ mamaBear: 'middle-size porridge pot',24+ littleBear: 'A little, small, wee pot',25+}))26+27+export const BearNames = () => {28+ const names = useMeals((state) => Object.keys(state))29+30+ return <div>{names.join(', ')}</div>31+}32+```33+34+Now papa bear wants a pizza instead:35+36+```js37+useMeals.setState({38+ papaBear: 'a large pizza',39+})40+```41+42+This change causes `BearNames` rerenders even though the actual output of `names` has not changed according to shallow equal.43+44+We can fix that using `useShallow`!45+46+```js47+import { create } from 'zustand'48+import { useShallow } from 'zustand/react/shallow'49+50+const useMeals = create(() => ({51+ papaBear: 'large porridge-pot',52+ mamaBear: 'middle-size porridge pot',53+ littleBear: 'A little, small, wee pot',54+}))55+56+export const BearNames = () => {57+ const names = useMeals(useShallow((state) => Object.keys(state)))58+59+ return <div>{names.join(', ')}</div>60+}61+```62+63+Now they can all order other meals without causing unnecessary rerenders of our `BearNames` component.added:docs/learn/guides/slices-pattern.md+120 added
1+---2+title: Slices Pattern3+nav: 64+---5+6+## Slicing the store into smaller stores7+8+Your store can become bigger and bigger and tougher to maintain as you add more features.9+10+You can divide your main store into smaller individual stores to achieve modularity. This is simple to accomplish in Zustand!11+12+The first individual store:13+14+```js15+export const createFishSlice = (set) => ({16+ fishes: 0,17+ addFish: () => set((state) => ({ fishes: state.fishes + 1 })),18+})19+```20+21+Another individual store:22+23+```js24+export const createBearSlice = (set) => ({25+ bears: 0,26+ addBear: () => set((state) => ({ bears: state.bears + 1 })),27+ eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),28+})29+```30+31+You can now combine both the stores into **one bounded store**:32+33+```js34+import { create } from 'zustand'35+import { createBearSlice } from './bearSlice'36+import { createFishSlice } from './fishSlice'37+38+export const useBoundStore = create((...a) => ({39+ ...createBearSlice(...a),40+ ...createFishSlice(...a),41+}))42+```43+44+### Usage in a React component45+46+```jsx47+import { useBoundStore } from './stores/useBoundStore'48+49+function App() {50+ const bears = useBoundStore((state) => state.bears)51+ const fishes = useBoundStore((state) => state.fishes)52+ const addBear = useBoundStore((state) => state.addBear)53+ return (54+ <div>55+ <h2>Number of bears: {bears}</h2>56+ <h2>Number of fishes: {fishes}</h2>57+ <button onClick={() => addBear()}>Add a bear</button>58+ </div>59+ )60+}61+62+export default App63+```64+65+### Updating multiple stores66+67+You can update multiple stores, at the same time, in a single function.68+69+```js70+export const createBearFishSlice = (set, get) => ({71+ addBearAndFish: () => {72+ get().addBear()73+ get().addFish()74+ },75+})76+```77+78+Combining all the stores together is the same as before.79+80+```js81+import { create } from 'zustand'82+import { createBearSlice } from './bearSlice'83+import { createFishSlice } from './fishSlice'84+import { createBearFishSlice } from './createBearFishSlice'85+86+export const useBoundStore = create((...a) => ({87+ ...createBearSlice(...a),88+ ...createFishSlice(...a),89+ ...createBearFishSlice(...a),90+}))91+```92+93+## Adding middlewares94+95+Adding middlewares to a combined store is the same as with other normal stores.96+97+Adding [`persist` middleware](../../reference/integrations/persisting-store-data.md) to our `useBoundStore`:98+99+```js100+import { create } from 'zustand'101+import { createBearSlice } from './bearSlice'102+import { createFishSlice } from './fishSlice'103+import { persist } from 'zustand/middleware'104+105+export const useBoundStore = create(106+ persist(107+ (...a) => ({108+ ...createBearSlice(...a),109+ ...createFishSlice(...a),110+ }),111+ { name: 'bound-store' },112+ ),113+)114+```115+116+Please keep in mind you should only apply middlewares in the combined store. Applying them inside individual slices can lead to unexpected issues.117+118+## Usage with TypeScript119+120+A detailed guide on how to use the slice pattern in Zustand with TypeScript can be found [here](./advanced-typescript.md#slices-pattern).added:docs/learn/guides/ssr-and-hydration.md+198 added
1+---2+title: SSR and Hydration3+nav: 164+---5+6+## Server-side Rendering (SSR)7+8+Server-side Rendering (SSR) is a technique that helps us render our components into9+HTML strings on the server, send them directly to the browser, and finally "hydrate" the10+static markup into a fully interactive app on the client.11+12+### React13+14+Let's say we want to render a stateless app using React. In order to do that, we need15+to use `express`, `react` and `react-dom/server`. We don't need `react-dom/client`16+since it's a stateless app.17+18+Let's dive into that:19+20+- `express` helps us build a web app that we can run using Node,21+- `react` helps us build the UI components that we use in our app,22+- `react-dom/server` helps us render our components on a server.23+24+```json25+// tsconfig.json26+{27+ "compilerOptions": {28+ "noImplicitAny": false,29+ "noEmitOnError": true,30+ "removeComments": false,31+ "sourceMap": true,32+ "target": "esnext"33+ },34+ "include": ["**/*"]35+}36+```37+38+> **Note:** do not forget to remove all comments from your `tsconfig.json` file.39+40+```tsx41+// app.tsx42+export const App = () => {43+ return (44+ <html>45+ <head>46+ <meta charSet="utf-8" />47+ <meta name="viewport" content="width=device-width, initial-scale=1" />48+ <title>Static Server-side-rendered App</title>49+ </head>50+ <body>51+ <div>Hello World!</div>52+ </body>53+ </html>54+ )55+}56+```57+58+```tsx59+// server.tsx60+import express from 'express'61+import React from 'react'62+import ReactDOMServer from 'react-dom/server'63+64+import { App } from './app.tsx'65+66+const port = Number.parseInt(process.env.PORT || '3000', 10)67+const app = express()68+69+app.get('/', (_, res) => {70+ const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {71+ onShellReady() {72+ res.setHeader('content-type', 'text/html')73+ pipe(res)74+ },75+ })76+})77+78+app.listen(port, () => {79+ console.log(`Server is listening at ${port}`)80+})81+```82+83+```sh84+tsc --build85+```86+87+```sh88+node server.js89+```90+91+## Hydration92+93+Hydration turns the initial HTML snapshot from the server into a fully interactive app94+that runs in the browser. The right way to "hydrate" a component is by using `hydrateRoot`.95+96+### React97+98+Let's say we want to render a stateful app using React. In order to do that we need to99+use `express`, `react`, `react-dom/server` and `react-dom/client`.100+101+Let's dive into that:102+103+- `express` helps us build a web app that we can run using Node,104+- `react` helps us build the UI components that we use in our app,105+- `react-dom/server` helps us render our components on a server,106+- `react-dom/client` helps us hydrate our components on a client.107+108+> **Note:** Do not forget that even if we can render our components on a server, it is109+> important to "hydrate" them on a client to make them interactive.110+111+```json112+// tsconfig.json113+{114+ "compilerOptions": {115+ "noImplicitAny": false,116+ "noEmitOnError": true,117+ "removeComments": false,118+ "sourceMap": true,119+ "target": "esnext"120+ },121+ "include": ["**/*"]122+}123+```124+125+> **Note:** do not forget to remove all comments in your `tsconfig.json` file.126+127+```tsx128+// app.tsx129+export const App = () => {130+ return (131+ <html>132+ <head>133+ <meta charSet="utf-8" />134+ <meta name="viewport" content="width=device-width, initial-scale=1" />135+ <title>Static Server-side-rendered App</title>136+ </head>137+ <body>138+ <div>Hello World!</div>139+ </body>140+ </html>141+ )142+}143+```144+145+```tsx146+// main.tsx147+import ReactDOMClient from 'react-dom/client'148+149+import { App } from './app.tsx'150+151+ReactDOMClient.hydrateRoot(document, <App />)152+```153+154+```tsx155+// server.tsx156+import express from 'express'157+import React from 'react'158+import ReactDOMServer from 'react-dom/server'159+160+import { App } from './app.tsx'161+162+const port = Number.parseInt(process.env.PORT || '3000', 10)163+const app = express()164+165+app.use('/', (_, res) => {166+ const { pipe } = ReactDOMServer.renderToPipeableStream(<App />, {167+ bootstrapScripts: ['/main.js'],168+ onShellReady() {169+ res.setHeader('content-type', 'text/html')170+ pipe(res)171+ },172+ })173+})174+175+app.listen(port, () => {176+ console.log(`Server is listening at ${port}`)177+})178+```179+180+```sh181+tsc --build182+```183+184+```sh185+node server.js186+```187+188+> **Warning:** The React tree you pass to `hydrateRoot` needs to produce the same output as it did on the server.189+> The most common causes leading to hydration errors include:190+>191+> - Extra whitespace (like newlines) around the React-generated HTML inside the root node.192+> - Using checks like typeof window !== 'undefined' in your rendering logic.193+> - Using browser-only APIs like `window.matchMedia` in your rendering logic.194+> - Rendering different data on the server and the client.195+>196+> React recovers from some hydration errors, but you must fix them like other bugs. In the best case, they’ll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.197+198+You can read more about the caveats and pitfalls here: [hydrateRoot](https://react.dev/reference/react-dom/client/hydrateRoot)added:docs/learn/guides/testing.md+741 added
1+---2+title: Testing3+description: Writing Tests4+nav: 185+---6+7+## Setting Up a Test Environment8+9+### Test Runners10+11+Usually, your test runner needs to be configured to run JavaScript/TypeScript syntax. If you're12+going to be testing UI components, you will likely need to configure the test runner to use JSDOM13+to provide a mock DOM environment.14+15+See these resources for test runner configuration instructions:16+17+- **Jest**18+ - [Jest: Getting Started](https://jestjs.io/docs/getting-started)19+ - [Jest: Configuration - Test Environment](https://jestjs.io/docs/configuration#testenvironment-string)20+- **Vitest**21+ - [Vitest: Getting Started](https://vitest.dev/guide)22+ - [Vitest: Configuration - Test Environment](https://vitest.dev/config/#environment)23+24+### UI and Network Testing Tools25+26+**We recommend using [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)27+to test out React components that connect to Zustand**. RTL is a simple and complete React DOM28+testing utility that encourages good testing practices. It uses ReactDOM's `render` function and29+`act` from `react-dom/tests-utils`. Furthermore, [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)30+is the alternative to RTL to test out React Native components. The [Testing Library](https://testing-library.com/)31+family of tools also includes adapters for many other popular frameworks.32+33+We also recommend using [Mock Service Worker (MSW)](https://mswjs.io/) to mock network requests, as34+this means your application logic does not need to be changed or mocked when writing tests.35+36+- **React Testing Library (DOM)**37+ - [DOM Testing Library: Setup](https://testing-library.com/docs/dom-testing-library/setup)38+ - [React Testing Library: Setup](https://testing-library.com/docs/react-testing-library/setup)39+ - [Testing Library Jest-DOM Matchers](https://testing-library.com/docs/ecosystem-jest-dom)40+- **Native Testing Library (React Native)**41+ - [Native Testing Library: Setup](https://testing-library.com/docs/react-native-testing-library/setup)42+- **User Event Testing Library (DOM)**43+ - [User Event Testing Library: Setup](https://testing-library.com/docs/user-event/setup)44+- **TypeScript for Jest**45+ - [TypeScript for Jest: Setup](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation)46+- **TypeScript for Node**47+ - [TypeScript for Node: Setup](https://typestrong.org/ts-node/docs/installation)48+- **Mock Service Worker**49+ - [MSW: Installation](https://mswjs.io/docs/getting-started/install)50+ - [MSW: Setting up mock requests](https://mswjs.io/docs/getting-started/mocks/rest-api)51+ - [MSW: Mock server configuration for Node](https://mswjs.io/docs/getting-started/integrate/node)52+53+## Setting Up Zustand for testing54+55+> **Note**: Since Jest and Vitest have slight differences, like Vitest using **ES modules** and Jest using56+> **CommonJS modules**, you need to keep that in mind if you are using Vitest instead of Jest.57+58+The mock provided below will enable the relevant test runner to reset the zustand stores after each test.59+60+### Shared code just for testing purposes61+62+This shared code was added to avoid code duplication in our demo since we use the same counter store63+creator for both implementations, with and without `Context` API — `createStore` and `create`, respectively.64+65+```ts66+// shared/counter-store-creator.ts67+import { type StateCreator } from 'zustand'68+69+export type CounterStore = {70+ count: number71+ inc: () => void72+}73+74+export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({75+ count: 1,76+ inc: () => set((state) => ({ count: state.count + 1 })),77+})78+```79+80+### Jest81+82+In the next steps we are going to setup our Jest environment in order to mock Zustand.83+84+```ts85+// __mocks__/zustand.ts86+import { act } from '@testing-library/react'87+import type * as ZustandExportedTypes from 'zustand'88+export * from 'zustand'89+90+const { create: actualCreate, createStore: actualCreateStore } =91+ jest.requireActual<typeof ZustandExportedTypes>('zustand')92+93+// a variable to hold reset functions for all stores declared in the app94+export const storeResetFns = new Set<() => void>()95+96+const createUncurried = <T>(97+ stateCreator: ZustandExportedTypes.StateCreator<T>,98+) => {99+ const store = actualCreate(stateCreator)100+ const initialState = store.getInitialState()101+ storeResetFns.add(() => {102+ store.setState(initialState, true)103+ })104+ return store105+}106+107+// when creating a store, we get its initial state, create a reset function and add it in the set108+export const create = (<T>(109+ stateCreator: ZustandExportedTypes.StateCreator<T>,110+) => {111+ console.log('zustand create mock')112+113+ // to support curried version of create114+ return typeof stateCreator === 'function'115+ ? createUncurried(stateCreator)116+ : createUncurried117+}) as typeof ZustandExportedTypes.create118+119+const createStoreUncurried = <T>(120+ stateCreator: ZustandExportedTypes.StateCreator<T>,121+) => {122+ const store = actualCreateStore(stateCreator)123+ const initialState = store.getInitialState()124+ storeResetFns.add(() => {125+ store.setState(initialState, true)126+ })127+ return store128+}129+130+// when creating a store, we get its initial state, create a reset function and add it in the set131+export const createStore = (<T>(132+ stateCreator: ZustandExportedTypes.StateCreator<T>,133+) => {134+ console.log('zustand createStore mock')135+136+ // to support curried version of createStore137+ return typeof stateCreator === 'function'138+ ? createStoreUncurried(stateCreator)139+ : createStoreUncurried140+}) as typeof ZustandExportedTypes.createStore141+142+// reset all stores after each test run143+afterEach(() => {144+ act(() => {145+ storeResetFns.forEach((resetFn) => {146+ resetFn()147+ })148+ })149+})150+```151+152+```ts153+// setup-jest.ts154+import '@testing-library/jest-dom'155+```156+157+```ts158+// jest.config.ts159+import type { JestConfigWithTsJest } from 'ts-jest'160+161+const config: JestConfigWithTsJest = {162+ preset: 'ts-jest',163+ testEnvironment: 'jsdom',164+ setupFilesAfterEnv: ['./setup-jest.ts'],165+}166+167+export default config168+```169+170+> **Note**: to use TypeScript we need to install two packages `ts-jest` and `ts-node`.171+172+### Vitest173+174+In the next steps we are going to setup our Vitest environment in order to mock Zustand.175+176+> **Warning:** In Vitest you can change the [root](https://vitest.dev/config/#root).177+> Due to that, you need make sure that you are creating your `__mocks__` directory in the right place.178+> Let's say that you change the **root** to `./src`, that means you need to create a `__mocks__`179+> directory under `./src`. The end result would be `./src/__mocks__`, rather than `./__mocks__`.180+> Creating `__mocks__` directory in the wrong place can lead to issues when using Vitest.181+182+```ts183+// __mocks__/zustand.ts184+import { act } from '@testing-library/react'185+import type * as ZustandExportedTypes from 'zustand'186+export * from 'zustand'187+188+const { create: actualCreate, createStore: actualCreateStore } =189+ await vi.importActual<typeof ZustandExportedTypes>('zustand')190+191+// a variable to hold reset functions for all stores declared in the app192+export const storeResetFns = new Set<() => void>()193+194+const createUncurried = <T>(195+ stateCreator: ZustandExportedTypes.StateCreator<T>,196+) => {197+ const store = actualCreate(stateCreator)198+ const initialState = store.getInitialState()199+ storeResetFns.add(() => {200+ store.setState(initialState, true)201+ })202+ return store203+}204+205+// when creating a store, we get its initial state, create a reset function and add it in the set206+export const create = (<T>(207+ stateCreator: ZustandExportedTypes.StateCreator<T>,208+) => {209+ console.log('zustand create mock')210+211+ // to support curried version of create212+ return typeof stateCreator === 'function'213+ ? createUncurried(stateCreator)214+ : createUncurried215+}) as typeof ZustandExportedTypes.create216+217+const createStoreUncurried = <T>(218+ stateCreator: ZustandExportedTypes.StateCreator<T>,219+) => {220+ const store = actualCreateStore(stateCreator)221+ const initialState = store.getInitialState()222+ storeResetFns.add(() => {223+ store.setState(initialState, true)224+ })225+ return store226+}227+228+// when creating a store, we get its initial state, create a reset function and add it in the set229+export const createStore = (<T>(230+ stateCreator: ZustandExportedTypes.StateCreator<T>,231+) => {232+ console.log('zustand createStore mock')233+234+ // to support curried version of createStore235+ return typeof stateCreator === 'function'236+ ? createStoreUncurried(stateCreator)237+ : createStoreUncurried238+}) as typeof ZustandExportedTypes.createStore239+240+// reset all stores after each test run241+afterEach(() => {242+ act(() => {243+ storeResetFns.forEach((resetFn) => {244+ resetFn()245+ })246+ })247+})248+```249+250+> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need251+> to add `import { afterEach, vi } from 'vitest'` at the top.252+253+```ts254+// global.d.ts255+/// <reference types="vite/client" />256+/// <reference types="vitest/globals" />257+```258+259+> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we do260+> need to remove `/// <reference types="vitest/globals" />`.261+262+```ts263+// setup-vitest.ts264+import '@testing-library/jest-dom/vitest'265+266+vi.mock('zustand') // to make it work like Jest (auto-mocking)267+```268+269+> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need270+> to add `import { vi } from 'vitest'` at the top.271+272+```ts273+// vitest.config.ts274+import { defineConfig, mergeConfig } from 'vitest/config'275+import viteConfig from './vite.config'276+277+export default defineConfig((configEnv) =>278+ mergeConfig(279+ viteConfig(configEnv),280+ defineConfig({281+ test: {282+ globals: true,283+ environment: 'jsdom',284+ setupFiles: ['./setup-vitest.ts'],285+ },286+ }),287+ ),288+)289+```290+291+### Testing Components292+293+In the next examples we are going to use `useCounterStore`294+295+> **Note**: all of these examples are written using TypeScript.296+297+```ts298+// shared/counter-store-creator.ts299+import { type StateCreator } from 'zustand'300+301+export type CounterStore = {302+ count: number303+ inc: () => void304+}305+306+export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({307+ count: 1,308+ inc: () => set((state) => ({ count: state.count + 1 })),309+})310+```311+312+```ts313+// stores/use-counter-store.ts314+import { create } from 'zustand'315+316+import {317+ type CounterStore,318+ counterStoreCreator,319+} from '../shared/counter-store-creator'320+321+export const useCounterStore = create<CounterStore>()(counterStoreCreator)322+```323+324+```tsx325+// contexts/use-counter-store-context.tsx326+import { type ReactNode, createContext, useContext, useState } from 'react'327+import { createStore } from 'zustand'328+import { useStoreWithEqualityFn } from 'zustand/traditional'329+import { shallow } from 'zustand/shallow'330+331+import {332+ type CounterStore,333+ counterStoreCreator,334+} from '../shared/counter-store-creator'335+336+export const createCounterStore = () => {337+ return createStore<CounterStore>(counterStoreCreator)338+}339+340+export type CounterStoreApi = ReturnType<typeof createCounterStore>341+342+export const CounterStoreContext = createContext<CounterStoreApi | undefined>(343+ undefined,344+)345+346+export interface CounterStoreProviderProps {347+ children: ReactNode348+}349+350+export const CounterStoreProvider = ({351+ children,352+}: CounterStoreProviderProps) => {353+ const [store] = useState(() => createCounterStore())354+ return (355+ <CounterStoreContext.Provider value={store}>356+ {children}357+ </CounterStoreContext.Provider>358+ )359+}360+361+export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T362+363+export const useCounterStoreContext = <T,>(364+ selector: UseCounterStoreContextSelector<T>,365+): T => {366+ const counterStoreContext = useContext(CounterStoreContext)367+368+ if (counterStoreContext === undefined) {369+ throw new Error(370+ 'useCounterStoreContext must be used within CounterStoreProvider',371+ )372+ }373+374+ return useStoreWithEqualityFn(counterStoreContext, selector, shallow)375+}376+```377+378+```tsx379+// components/counter/counter.tsx380+import { useCounterStore } from '../../stores/use-counter-store'381+382+export function Counter() {383+ const { count, inc } = useCounterStore()384+385+ return (386+ <div>387+ <h2>Counter Store</h2>388+ <h4>{count}</h4>389+ <button onClick={inc}>One Up</button>390+ </div>391+ )392+}393+```394+395+```ts396+// components/counter/index.ts397+export * from './counter'398+```399+400+```tsx401+// components/counter/counter.test.tsx402+import { act, render, screen } from '@testing-library/react'403+import userEvent from '@testing-library/user-event'404+405+import { Counter } from './counter'406+407+describe('Counter', () => {408+ test('should render with initial state of 1', async () => {409+ renderCounter()410+411+ expect(await screen.findByText(/^1$/)).toBeInTheDocument()412+ expect(413+ await screen.findByRole('button', { name: /one up/i }),414+ ).toBeInTheDocument()415+ })416+417+ test('should increase count by clicking a button', async () => {418+ const user = userEvent.setup()419+420+ renderCounter()421+422+ expect(await screen.findByText(/^1$/)).toBeInTheDocument()423+424+ await user.click(await screen.findByRole('button', { name: /one up/i }))425+426+ expect(await screen.findByText(/^2$/)).toBeInTheDocument()427+ })428+})429+430+const renderCounter = () => {431+ return render(<Counter />)432+}433+```434+435+```tsx436+// components/counter-with-context/counter-with-context.tsx437+import {438+ CounterStoreProvider,439+ useCounterStoreContext,440+} from '../../contexts/use-counter-store-context'441+442+const Counter = () => {443+ const { count, inc } = useCounterStoreContext((state) => state)444+445+ return (446+ <div>447+ <h2>Counter Store Context</h2>448+ <h4>{count}</h4>449+ <button onClick={inc}>One Up</button>450+ </div>451+ )452+}453+454+export const CounterWithContext = () => {455+ return (456+ <CounterStoreProvider>457+ <Counter />458+ </CounterStoreProvider>459+ )460+}461+```462+463+```tsx464+// components/counter-with-context/index.ts465+export * from './counter-with-context'466+```467+468+```tsx469+// components/counter-with-context/counter-with-context.test.tsx470+import { act, render, screen } from '@testing-library/react'471+import userEvent from '@testing-library/user-event'472+473+import { CounterWithContext } from './counter-with-context'474+475+describe('CounterWithContext', () => {476+ test('should render with initial state of 1', async () => {477+ renderCounterWithContext()478+479+ expect(await screen.findByText(/^1$/)).toBeInTheDocument()480+ expect(481+ await screen.findByRole('button', { name: /one up/i }),482+ ).toBeInTheDocument()483+ })484+485+ test('should increase count by clicking a button', async () => {486+ const user = userEvent.setup()487+488+ renderCounterWithContext()489+490+ expect(await screen.findByText(/^1$/)).toBeInTheDocument()491+492+ await user.click(await screen.findByRole('button', { name: /one up/i }))493+494+ expect(await screen.findByText(/^2$/)).toBeInTheDocument()495+ })496+})497+498+const renderCounterWithContext = () => {499+ return render(<CounterWithContext />)500+}501+```502+503+> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need504+> to add `import { describe, test, expect } from 'vitest'` at the top of each test file.505+506+### Testing Stores507+508+In the next examples we are going to use `useCounterStore`509+510+> **Note**: all of these examples are written using TypeScript.511+512+```ts513+// shared/counter-store-creator.ts514+import { type StateCreator } from 'zustand'515+516+export type CounterStore = {517+ count: number518+ inc: () => void519+}520+521+export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({522+ count: 1,523+ inc: () => set((state) => ({ count: state.count + 1 })),524+})525+```526+527+```ts528+// stores/use-counter-store.ts529+import { create } from 'zustand'530+531+import {532+ type CounterStore,533+ counterStoreCreator,534+} from '../shared/counter-store-creator'535+536+export const useCounterStore = create<CounterStore>()(counterStoreCreator)537+```538+539+```tsx540+// contexts/use-counter-store-context.tsx541+import { type ReactNode, createContext, useContext, useState } from 'react'542+import { createStore } from 'zustand'543+import { useStoreWithEqualityFn } from 'zustand/traditional'544+import { shallow } from 'zustand/shallow'545+546+import {547+ type CounterStore,548+ counterStoreCreator,549+} from '../shared/counter-store-creator'550+551+export const createCounterStore = () => {552+ return createStore<CounterStore>(counterStoreCreator)553+}554+555+export type CounterStoreApi = ReturnType<typeof createCounterStore>556+557+export const CounterStoreContext = createContext<CounterStoreApi | undefined>(558+ undefined,559+)560+561+export interface CounterStoreProviderProps {562+ children: ReactNode563+}564+565+export const CounterStoreProvider = ({566+ children,567+}: CounterStoreProviderProps) => {568+ const [store] = useState(() => createCounterStore())569+ return (570+ <CounterStoreContext.Provider value={store}>571+ {children}572+ </CounterStoreContext.Provider>573+ )574+}575+576+export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T577+578+export const useCounterStoreContext = <T,>(579+ selector: UseCounterStoreContextSelector<T>,580+): T => {581+ const counterStoreContext = useContext(CounterStoreContext)582+583+ if (counterStoreContext === undefined) {584+ throw new Error(585+ 'useCounterStoreContext must be used within CounterStoreProvider',586+ )587+ }588+589+ return useStoreWithEqualityFn(counterStoreContext, selector, shallow)590+}591+```592+593+```tsx594+// components/counter/counter.tsx595+import { useCounterStore } from '../../stores/use-counter-store'596+597+export function Counter() {598+ const { count, inc } = useCounterStore()599+600+ return (601+ <div>602+ <h2>Counter Store</h2>603+ <h4>{count}</h4>604+ <button onClick={inc}>One Up</button>605+ </div>606+ )607+}608+```609+610+```ts611+// components/counter/index.ts612+export * from './counter'613+```614+615+```tsx616+// components/counter/counter.test.tsx617+import { act, render, screen } from '@testing-library/react'618+import userEvent from '@testing-library/user-event'619+620+import { Counter, useCounterStore } from '../../../stores/use-counter-store.ts'621+622+describe('Counter', () => {623+ test('should render with initial state of 1', async () => {624+ renderCounter()625+626+ expect(useCounterStore.getState().count).toBe(1)627+ })628+629+ test('should increase count by clicking a button', async () => {630+ const user = userEvent.setup()631+632+ renderCounter()633+634+ expect(useCounterStore.getState().count).toBe(1)635+636+ await user.click(await screen.findByRole('button', { name: /one up/i }))637+638+ expect(useCounterStore.getState().count).toBe(2)639+ })640+})641+642+const renderCounter = () => {643+ return render(<Counter />)644+}645+```646+647+```tsx648+// components/counter-with-context/counter-with-context.tsx649+import {650+ CounterStoreProvider,651+ useCounterStoreContext,652+} from '../../contexts/use-counter-store-context'653+654+const Counter = () => {655+ const { count, inc } = useCounterStoreContext((state) => state)656+657+ return (658+ <div>659+ <h2>Counter Store Context</h2>660+ <h4>{count}</h4>661+ <button onClick={inc}>One Up</button>662+ </div>663+ )664+}665+666+export const CounterWithContext = () => {667+ return (668+ <CounterStoreProvider>669+ <Counter />670+ </CounterStoreProvider>671+ )672+}673+```674+675+```tsx676+// components/counter-with-context/index.ts677+export * from './counter-with-context'678+```679+680+```tsx681+// components/counter-with-context/counter-with-context.test.tsx682+import { act, render, screen } from '@testing-library/react'683+import userEvent from '@testing-library/user-event'684+685+import { CounterStoreContext } from '../../../contexts/use-counter-store-context'686+import { counterStoreCreator } from '../../../shared/counter-store-creator'687+688+describe('CounterWithContext', () => {689+ test('should render with initial state of 1', async () => {690+ const counterStore = counterStoreCreator()691+692+ renderCounterWithContext(counterStore)693+694+ expect(counterStore.getState().count).toBe(1)695+ expect(696+ await screen.findByRole('button', { name: /one up/i }),697+ ).toBeInTheDocument()698+ })699+700+ test('should increase count by clicking a button', async () => {701+ const user = userEvent.setup()702+ const counterStore = counterStoreCreator()703+704+ renderCounterWithContext(counterStore)705+706+ expect(counterStore.getState().count).toBe(1)707+708+ await user.click(await screen.findByRole('button', { name: /one up/i }))709+710+ expect(counterStore.getState().count).toBe(2)711+ })712+})713+714+const renderCounterWithContext = (store) => {715+ return render(<CounterWithContext />, {716+ wrapper: ({ children }) => (717+ <CounterStoreContext.Provider value={store}>718+ {children}719+ </CounterStoreContext.Provider>720+ ),721+ })722+}723+```724+725+## References726+727+- **React Testing Library**: [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)728+ is a very lightweight solution for testing React components. It provides utility functions on top729+ of `react-dom` and `react-dom/test-utils`, in a way that encourages better testing practices. Its730+ primary guiding principle is: "The more your tests resemble the way your software is used, the731+ more confidence they can give you."732+- **Native Testing Library**: [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)733+ is a very lightweight solution for testing React Native components, similarly to RTL, but its734+ functions are built on top of `react-test-renderer`.735+- **Testing Implementation Details**: Blog post by Kent C. Dodds on why he recommends to avoid736+ [testing implementation details](https://kentcdodds.com/blog/testing-implementation-details).737+738+## Demos739+740+- Jest: https://stackblitz.com/edit/jest-zustand741+- Vitest: https://stackblitz.com/edit/vitest-zustandadded:docs/learn/guides/tutorial-tic-tac-toe.md+1429 added
1+---2+title: 'Tutorial: Tic-Tac-Toe'3+description: Building a game4+nav: 35+---6+7+# Tutorial: Tic-Tac-Toe8+9+## Building a game10+11+You will build a small tic-tac-toe game during this tutorial. This tutorial does assume existing12+React knowledge. The techniques you'll learn in the tutorial are fundamental to building any React13+app, and fully understanding it will give you a deep understanding of React and Zustand.14+15+> [!NOTE]16+> This tutorial is crafted for those who learn best through hands-on experience and want to swiftly17+> create something tangible. It draws inspiration from React's tic-tac-toe tutorial.18+19+The tutorial is divided into several sections:20+21+- Setup for the tutorial will give you a starting point to follow the tutorial.22+- Overview will teach you the fundamentals of React: components, props, and state.23+- Completing the game will teach you the most common techniques in React development.24+- Adding time travel will give you a deeper insight into the unique strengths of React.25+26+### What are you building?27+28+In this tutorial, you'll build an interactive tic-tac-toe game with React and Zustand.29+30+You can see what it will look like when you're finished here:31+32+```jsx33+import { create } from 'zustand'34+import { combine } from 'zustand/middleware'35+36+const useGameStore = create(37+ combine(38+ {39+ history: [Array(9).fill(null)],40+ currentMove: 0,41+ },42+ (set, get) => {43+ return {44+ setHistory: (nextHistory) => {45+ set((state) => ({46+ history:47+ typeof nextHistory === 'function'48+ ? nextHistory(state.history)49+ : nextHistory,50+ }))51+ },52+ setCurrentMove: (nextCurrentMove) => {53+ set((state) => ({54+ currentMove:55+ typeof nextCurrentMove === 'function'56+ ? nextCurrentMove(state.currentMove)57+ : nextCurrentMove,58+ }))59+ },60+ }61+ },62+ ),63+)64+65+function Square({ value, onSquareClick }) {66+ return (67+ <button68+ style={{69+ display: 'inline-flex',70+ alignItems: 'center',71+ justifyContent: 'center',72+ padding: 0,73+ backgroundColor: '#fff',74+ border: '1px solid #999',75+ outline: 0,76+ borderRadius: 0,77+ fontSize: '1rem',78+ fontWeight: 'bold',79+ }}80+ onClick={onSquareClick}81+ >82+ {value}83+ </button>84+ )85+}86+87+function Board({ xIsNext, squares, onPlay }) {88+ const winner = calculateWinner(squares)89+ const turns = calculateTurns(squares)90+ const player = xIsNext ? 'X' : 'O'91+ const status = calculateStatus(winner, turns, player)92+93+ function handleClick(i) {94+ if (squares[i] || winner) return95+ const nextSquares = squares.slice()96+ nextSquares[i] = player97+ onPlay(nextSquares)98+ }99+100+ return (101+ <>102+ <div style={{ marginBottom: '0.5rem' }}>{status}</div>103+ <div104+ style={{105+ display: 'grid',106+ gridTemplateColumns: 'repeat(3, 1fr)',107+ gridTemplateRows: 'repeat(3, 1fr)',108+ width: 'calc(3 * 2.5rem)',109+ height: 'calc(3 * 2.5rem)',110+ border: '1px solid #999',111+ }}112+ >113+ {squares.map((_, i) => (114+ <Square115+ key={`square-${i}`}116+ value={squares[i]}117+ onSquareClick={() => handleClick(i)}118+ />119+ ))}120+ </div>121+ </>122+ )123+}124+125+export default function Game() {126+ const history = useGameStore((state) => state.history)127+ const setHistory = useGameStore((state) => state.setHistory)128+ const currentMove = useGameStore((state) => state.currentMove)129+ const setCurrentMove = useGameStore((state) => state.setCurrentMove)130+ const xIsNext = currentMove % 2 === 0131+ const currentSquares = history[currentMove]132+133+ function handlePlay(nextSquares) {134+ const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]135+ setHistory(nextHistory)136+ setCurrentMove(nextHistory.length - 1)137+ }138+139+ function jumpTo(nextMove) {140+ setCurrentMove(nextMove)141+ }142+143+ return (144+ <div145+ style={{146+ display: 'flex',147+ flexDirection: 'row',148+ fontFamily: 'monospace',149+ }}150+ >151+ <div>152+ <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />153+ </div>154+ <div style={{ marginLeft: '1rem' }}>155+ <ol>156+ {history.map((_, historyIndex) => {157+ const description =158+ historyIndex > 0159+ ? `Go to move #${historyIndex}`160+ : 'Go to game start'161+162+ return (163+ <li key={historyIndex}>164+ <button onClick={() => jumpTo(historyIndex)}>165+ {description}166+ </button>167+ </li>168+ )169+ })}170+ </ol>171+ </div>172+ </div>173+ )174+}175+176+function calculateWinner(squares) {177+ const lines = [178+ [0, 1, 2],179+ [3, 4, 5],180+ [6, 7, 8],181+ [0, 3, 6],182+ [1, 4, 7],183+ [2, 5, 8],184+ [0, 4, 8],185+ [2, 4, 6],186+ ]187+188+ for (let i = 0; i < lines.length; i++) {189+ const [a, b, c] = lines[i]190+ if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {191+ return squares[a]192+ }193+ }194+195+ return null196+}197+198+function calculateTurns(squares) {199+ return squares.filter((square) => !square).length200+}201+202+function calculateStatus(winner, turns, player) {203+ if (!winner && !turns) return 'Draw'204+ if (winner) return `Winner ${winner}`205+ return `Next player: ${player}`206+}207+```208+209+### Building the board210+211+Let's start by creating the `Square` component, which will be a building block for our `Board`212+component. This component will represent each square in our game.213+214+The `Square` component should take `value` and `onSquareClick` as props. It should return a215+`<button>` element, styled to look like a square. The button displays the value prop, which can be216+`'X'`, `'O'`, or `null`, depending on the game's state. When the button is clicked, it triggers the217+`onSquareClick` function passed in as a prop, allowing the game to respond to user input.218+219+Here's the code for the `Square` component:220+221+```jsx222+function Square({ value, onSquareClick }) {223+ return (224+ <button225+ style={{226+ display: 'inline-flex',227+ alignItems: 'center',228+ justifyContent: 'center',229+ padding: 0,230+ backgroundColor: '#fff',231+ border: '1px solid #999',232+ outline: 0,233+ borderRadius: 0,234+ fontSize: '1rem',235+ fontWeight: 'bold',236+ }}237+ onClick={onSquareClick}238+ >239+ {value}240+ </button>241+ )242+}243+```244+245+Let's move on to creating the Board component, which will consist of 9 squares arranged in a grid.246+This component will serve as the main playing area for our game.247+248+The `Board` component should return a `<div>` element styled as a grid. The grid layout is achieved249+using CSS Grid, with three columns and three rows, each taking up an equal fraction of the available250+space. The overall size of the grid is determined by the width and height properties, ensuring that251+it is square-shaped and appropriately sized.252+253+Inside the grid, we place nine Square components, each with a value prop representing its position.254+These Square components will eventually hold the game symbols (`'X'` or `'O'`) and handle user255+interactions.256+257+Here's the code for the `Board` component:258+259+```jsx260+export default function Board() {261+ return (262+ <div263+ style={{264+ display: 'grid',265+ gridTemplateColumns: 'repeat(3, 1fr)',266+ gridTemplateRows: 'repeat(3, 1fr)',267+ width: 'calc(3 * 2.5rem)',268+ height: 'calc(3 * 2.5rem)',269+ border: '1px solid #999',270+ }}271+ >272+ <Square value="1" />273+ <Square value="2" />274+ <Square value="3" />275+ <Square value="4" />276+ <Square value="5" />277+ <Square value="6" />278+ <Square value="7" />279+ <Square value="8" />280+ <Square value="9" />281+ </div>282+ )283+}284+```285+286+This Board component sets up the basic structure for our game board by arranging nine squares in a287+3x3 grid. It positions the squares neatly, providing a foundation for adding more features and288+handling player interactions in the future.289+290+### Lifting state up291+292+Each `Square` component could maintain a part of the game's state. To check for a winner in a293+tic-tac-toe game, the `Board` component would need to somehow know the state of each of the 9294+`Square` components.295+296+How would you approach that? At first, you might guess that the `Board` component needs to ask each297+`Square` component for that `Square`'s component state. Although this approach is technically298+possible in React, we discourage it because the code becomes difficult to understand, susceptible299+to bugs, and hard to refactor. Instead, the best approach is to store the game's state in the300+parent `Board` component instead of in each `Square` component. The `Board` component can tell each301+`Square` component what to display by passing a prop, like you did when you passed a number to each302+`Square` component.303+304+> [!IMPORTANT]305+> To collect data from multiple children, or to have two or more child components306+> communicate with each other, declare the shared state in their parent component instead. The307+> parent component can pass that state back down to the children via props. This keeps the child308+> components in sync with each other and with their parent.309+310+Let's take this opportunity to try it out. Edit the `Board` component so that it declares a state311+variable named squares that defaults to an array of 9 nulls corresponding to the 9 squares:312+313+```jsx314+import { create } from 'zustand'315+import { combine } from 'zustand/middleware'316+317+const useGameStore = create(318+ combine({ squares: Array(9).fill(null) }, (set) => {319+ return {320+ setSquares: (nextSquares) => {321+ set((state) => ({322+ squares:323+ typeof nextSquares === 'function'324+ ? nextSquares(state.squares)325+ : nextSquares,326+ }))327+ },328+ }329+ }),330+)331+332+export default function Board() {333+ const squares = useGameStore((state) => state.squares)334+ const setSquares = useGameStore((state) => state.setSquares)335+336+ return (337+ <div338+ style={{339+ display: 'grid',340+ gridTemplateColumns: 'repeat(3, 1fr)',341+ gridTemplateRows: 'repeat(3, 1fr)',342+ width: 'calc(3 * 2.5rem)',343+ height: 'calc(3 * 2.5rem)',344+ border: '1px solid #999',345+ }}346+ >347+ {squares.map((square, squareIndex) => (348+ <Square key={squareIndex} value={square} />349+ ))}350+ </div>351+ )352+}353+```354+355+`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The356+`useGameStore` declares a `squares` state that's initially set to that array. Each entry in the357+array corresponds to the value of a square. When you fill the board in later, the squares array358+will look like this:359+360+```js361+const squares = ['O', null, 'X', 'X', 'X', 'O', 'O', null, null]362+```363+364+Each Square will now receive a `value` prop that will either be `'X'`, `'O'`, or `null` for empty365+squares.366+367+Next, you need to change what happens when a `Square` component is clicked. The `Board` component368+now maintains which squares are filled. You'll need to create a way for the `Square` component to369+update the `Board`'s component state. Since state is private to a component that defines it, you370+cannot update the `Board`'s component state directly from `Square` component.371+372+Instead, you'll pass down a function from the Board component to the `Square` component, and you'll373+have `Square` component call that function when a square is clicked. You'll start with the function374+that the `Square` component will call when it is clicked. You'll call that function `onSquareClick`:375+376+Now you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name377+`handleClick`. To connect `onSquareClick` to `handleClick` you'll pass an inline function to the378+`onSquareClick` prop of the first Square component:379+380+```jsx381+<Square key={squareIndex} value={square} onSquareClick={() => handleClick(i)} />382+```383+384+Lastly, you will define the `handleClick` function inside the `Board` component to update the385+squares array holding your board's state.386+387+The `handleClick` function should take the index of the square to update and create a copy of the388+`squares` array (`nextSquares`). Then, `handleClick` updates the `nextSquares` array by adding `X`389+to the square at the specified index (`i`) if is not already filled.390+391+```jsx {5-10,27}392+export default function Board() {393+ const squares = useGameStore((state) => state.squares)394+ const setSquares = useGameStore((state) => state.setSquares)395+396+ function handleClick(i) {397+ if (squares[i]) return398+ const nextSquares = squares.slice()399+ nextSquares[i] = 'X'400+ setSquares(nextSquares)401+ }402+403+ return (404+ <div405+ style={{406+ display: 'grid',407+ gridTemplateColumns: 'repeat(3, 1fr)',408+ gridTemplateRows: 'repeat(3, 1fr)',409+ width: 'calc(3 * 2.5rem)',410+ height: 'calc(3 * 2.5rem)',411+ border: '1px solid #999',412+ }}413+ >414+ {squares.map((square, squareIndex) => (415+ <Square416+ key={squareIndex}417+ value={square}418+ onSquareClick={() => handleClick(squareIndex)}419+ />420+ ))}421+ </div>422+ )423+}424+```425+426+> [!IMPORTANT]427+> Note how in `handleClick` function, you call `.slice()` to create a copy of the squares array428+> instead of modifying the existing array.429+430+### Taking turns431+432+It's now time to fix a major defect in this tic-tac-toe game: the `'O'`s cannot be used on the433+board.434+435+You'll set the first move to be `'X'` by default. Let's keep track of this by adding another piece436+of state to the `useGameStore` hook:437+438+```jsx {2,12-18}439+const useGameStore = create(440+ combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {441+ return {442+ setSquares: (nextSquares) => {443+ set((state) => ({444+ squares:445+ typeof nextSquares === 'function'446+ ? nextSquares(state.squares)447+ : nextSquares,448+ }))449+ },450+ setXIsNext: (nextXIsNext) => {451+ set((state) => ({452+ xIsNext:453+ typeof nextXIsNext === 'function'454+ ? nextXIsNext(state.xIsNext)455+ : nextXIsNext,456+ }))457+ },458+ }459+ }),460+)461+```462+463+Each time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next464+and the game's state will be saved. You'll update the Board's `handleClick` function to flip the465+value of `xIsNext`:466+467+```jsx {2-3,6,11}468+export default function Board() {469+ const xIsNext = useGameStore((state) => state.xIsNext)470+ const setXIsNext = useGameStore((state) => state.setXIsNext)471+ const squares = useGameStore((state) => state.squares)472+ const setSquares = useGameStore((state) => state.setSquares)473+ const player = xIsNext ? 'X' : 'O'474+475+ function handleClick(i) {476+ if (squares[i]) return477+ const nextSquares = squares.slice()478+ nextSquares[i] = player479+ setSquares(nextSquares)480+ setXIsNext(!xIsNext)481+ }482+483+ return (484+ <div485+ style={{486+ display: 'grid',487+ gridTemplateColumns: 'repeat(3, 1fr)',488+ gridTemplateRows: 'repeat(3, 1fr)',489+ width: 'calc(3 * 2.5rem)',490+ height: 'calc(3 * 2.5rem)',491+ border: '1px solid #999',492+ }}493+ >494+ {squares.map((square, squareIndex) => (495+ <Square496+ key={squareIndex}497+ value={square}498+ onSquareClick={() => handleClick(squareIndex)}499+ />500+ ))}501+ </div>502+ )503+}504+```505+506+### Declaring a winner or draw507+508+Now that the players can take turns, you'll want to show when the game is won or drawn and there509+are no more turns to make. To do this you'll add three helper functions. The first helper function510+called `calculateWinner` that takes an array of 9 squares, checks for a winner and returns `'X'`,511+`'O'`, or `null` as appropriate. The second helper function called `calculateTurns` that takes the512+same array, checks for remaining turns by filtering out only `null` items, and returns the count of513+them. The last helper called `calculateStatus` that takes the remaining turns, the winner, and the514+current player (`'X' or 'O'`):515+516+```js517+function calculateWinner(squares) {518+ const lines = [519+ [0, 1, 2],520+ [3, 4, 5],521+ [6, 7, 8],522+ [0, 3, 6],523+ [1, 4, 7],524+ [2, 5, 8],525+ [0, 4, 8],526+ [2, 4, 6],527+ ]528+529+ for (let i = 0; i < lines.length; i++) {530+ const [a, b, c] = lines[i]531+ if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {532+ return squares[a]533+ }534+ }535+536+ return null537+}538+539+function calculateTurns(squares) {540+ return squares.filter((square) => !square).length541+}542+543+function calculateStatus(winner, turns, player) {544+ if (!winner && !turns) return 'Draw'545+ if (winner) return `Winner ${winner}`546+ return `Next player: ${player}`547+}548+```549+550+You will use the result of `calculateWinner(squares)` in the Board component's `handleClick`551+function to check if a player has won. You can perform this check at the same time you check if a552+user has clicked a square that already has a `'X'` or and `'O'`. We'd like to return early in553+both cases:554+555+```js {2}556+function handleClick(i) {557+ if (squares[i] || winner) return558+ const nextSquares = squares.slice()559+ nextSquares[i] = player560+ setSquares(nextSquares)561+ setXIsNext(!xIsNext)562+}563+```564+565+To let the players know when the game is over, you can display text such as `'Winner: X'` or566+`'Winner: O'`. To do that you'll add a `status` section to the `Board` component. The status will567+display the winner or draw if the game is over and if the game is ongoing you'll display which568+player's turn is next:569+570+```jsx {6-7,9,21}571+export default function Board() {572+ const xIsNext = useGameStore((state) => state.xIsNext)573+ const setXIsNext = useGameStore((state) => state.setXIsNext)574+ const squares = useGameStore((state) => state.squares)575+ const setSquares = useGameStore((state) => state.setSquares)576+ const winner = calculateWinner(squares)577+ const turns = calculateTurns(squares)578+ const player = xIsNext ? 'X' : 'O'579+ const status = calculateStatus(winner, turns, player)580+581+ function handleClick(i) {582+ if (squares[i] || winner) return583+ const nextSquares = squares.slice()584+ nextSquares[i] = player585+ setSquares(nextSquares)586+ setXIsNext(!xIsNext)587+ }588+589+ return (590+ <>591+ <div style={{ marginBottom: '0.5rem' }}>{status}</div>592+ <div593+ style={{594+ display: 'grid',595+ gridTemplateColumns: 'repeat(3, 1fr)',596+ gridTemplateRows: 'repeat(3, 1fr)',597+ width: 'calc(3 * 2.5rem)',598+ height: 'calc(3 * 2.5rem)',599+ border: '1px solid #999',600+ }}601+ >602+ {squares.map((square, squareIndex) => (603+ <Square604+ key={squareIndex}605+ value={square}606+ onSquareClick={() => handleClick(squareIndex)}607+ />608+ ))}609+ </div>610+ </>611+ )612+}613+```614+615+Congratulations! You now have a working tic-tac-toe game. And you've just learned the basics of616+React and Zustand too. So you are the real winner here. Here is what the code should look like:617+618+```jsx619+import { create } from 'zustand'620+import { combine } from 'zustand/middleware'621+622+const useGameStore = create(623+ combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {624+ return {625+ setSquares: (nextSquares) => {626+ set((state) => ({627+ squares:628+ typeof nextSquares === 'function'629+ ? nextSquares(state.squares)630+ : nextSquares,631+ }))632+ },633+ setXIsNext: (nextXIsNext) => {634+ set((state) => ({635+ xIsNext:636+ typeof nextXIsNext === 'function'637+ ? nextXIsNext(state.xIsNext)638+ : nextXIsNext,639+ }))640+ },641+ }642+ }),643+)644+645+function Square({ value, onSquareClick }) {646+ return (647+ <button648+ style={{649+ display: 'inline-flex',650+ alignItems: 'center',651+ justifyContent: 'center',652+ padding: 0,653+ backgroundColor: '#fff',654+ border: '1px solid #999',655+ outline: 0,656+ borderRadius: 0,657+ fontSize: '1rem',658+ fontWeight: 'bold',659+ }}660+ onClick={onSquareClick}661+ >662+ {value}663+ </button>664+ )665+}666+667+export default function Board() {668+ const xIsNext = useGameStore((state) => state.xIsNext)669+ const setXIsNext = useGameStore((state) => state.setXIsNext)670+ const squares = useGameStore((state) => state.squares)671+ const setSquares = useGameStore((state) => state.setSquares)672+ const winner = calculateWinner(squares)673+ const turns = calculateTurns(squares)674+ const player = xIsNext ? 'X' : 'O'675+ const status = calculateStatus(winner, turns, player)676+677+ function handleClick(i) {678+ if (squares[i] || winner) return679+ const nextSquares = squares.slice()680+ nextSquares[i] = player681+ setSquares(nextSquares)682+ setXIsNext(!xIsNext)683+ }684+685+ return (686+ <>687+ <div style={{ marginBottom: '0.5rem' }}>{status}</div>688+ <div689+ style={{690+ display: 'grid',691+ gridTemplateColumns: 'repeat(3, 1fr)',692+ gridTemplateRows: 'repeat(3, 1fr)',693+ width: 'calc(3 * 2.5rem)',694+ height: 'calc(3 * 2.5rem)',695+ border: '1px solid #999',696+ }}697+ >698+ {squares.map((square, squareIndex) => (699+ <Square700+ key={squareIndex}701+ value={square}702+ onSquareClick={() => handleClick(squareIndex)}703+ />704+ ))}705+ </div>706+ </>707+ )708+}709+710+function calculateWinner(squares) {711+ const lines = [712+ [0, 1, 2],713+ [3, 4, 5],714+ [6, 7, 8],715+ [0, 3, 6],716+ [1, 4, 7],717+ [2, 5, 8],718+ [0, 4, 8],719+ [2, 4, 6],720+ ]721+722+ for (let i = 0; i < lines.length; i++) {723+ const [a, b, c] = lines[i]724+ if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {725+ return squares[a]726+ }727+ }728+729+ return null730+}731+732+function calculateTurns(squares) {733+ return squares.filter((square) => !square).length734+}735+736+function calculateStatus(winner, turns, player) {737+ if (!winner && !turns) return 'Draw'738+ if (winner) return `Winner ${winner}`739+ return `Next player: ${player}`740+}741+```742+743+### Adding time travel744+745+As a final exercise, let's make it possible to “go back in time” and revisit previous moves in the746+game.747+748+If you had directly modified the squares array, implementing this time-travel feature would be very749+difficult. However, since you used `slice()` to create a new copy of the squares array after every750+move, treating it as immutable, you can store every past version of the squares array and navigate751+between them.752+753+You'll keep track of these past squares arrays in a new state variable called `history`. This754+`history` array will store all board states, from the first move to the latest one, and will look755+something like this:756+757+```js758+const history = [759+ // First move760+ [null, null, null, null, null, null, null, null, null],761+ // Second move762+ ['X', null, null, null, null, null, null, null, null],763+ // Third move764+ ['X', 'O', null, null, null, null, null, null, null],765+ // and so on...766+]767+```768+769+This approach allows you to easily navigate between different game states and implement the770+time-travel feature.771+772+### Lifting state up, again773+774+Next, you will create a new top-level component called `Game` to display a list of past moves. This775+is where you will store the `history` state that contains the entire game history.776+777+By placing the `history` state in the `Game` component, you can remove the `squares` state from the778+`Board` component. You will now lift the state up from the `Board` component to the top-level `Game`779+component. This change allows the `Game` component to have full control over the `Board`'s780+component data and instruct the `Board` component to render previous turns from the `history`.781+782+First, add a `Game` component with `export default` and remove it from `Board` component. Here is783+what the code should look like:784+785+```jsx {1,44-61}786+function Board() {787+ const xIsNext = useGameStore((state) => state.xIsNext)788+ const setXIsNext = useGameStore((state) => state.setXIsNext)789+ const squares = useGameStore((state) => state.squares)790+ const setSquares = useGameStore((state) => state.setSquares)791+ const winner = calculateWinner(squares)792+ const turns = calculateTurns(squares)793+ const player = xIsNext ? 'X' : 'O'794+ const status = calculateStatus(winner, turns, player)795+796+ function handleClick(i) {797+ if (squares[i] || winner) return798+ const nextSquares = squares.slice()799+ nextSquares[i] = player800+ setSquares(nextSquares)801+ setXIsNext(!xIsNext)802+ }803+804+ return (805+ <>806+ <div style={{ marginBottom: '0.5rem' }}>{status}</div>807+ <div808+ style={{809+ display: 'grid',810+ gridTemplateColumns: 'repeat(3, 1fr)',811+ gridTemplateRows: 'repeat(3, 1fr)',812+ width: 'calc(3 * 2.5rem)',813+ height: 'calc(3 * 2.5rem)',814+ border: '1px solid #999',815+ }}816+ >817+ {squares.map((square, squareIndex) => (818+ <Square819+ key={squareIndex}820+ value={square}821+ onSquareClick={() => handleClick(squareIndex)}822+ />823+ ))}824+ </div>825+ </>826+ )827+}828+829+export default function Game() {830+ return (831+ <div832+ style={{833+ display: 'flex',834+ flexDirection: 'row',835+ fontFamily: 'monospace',836+ }}837+ >838+ <div>839+ <Board />840+ </div>841+ <div style={{ marginLeft: '1rem' }}>842+ <ol>{/* TODO */}</ol>843+ </div>844+ </div>845+ )846+}847+```848+849+Add some state to the `useGameStore` hook to track the history of moves:850+851+```js {2,4-11}852+const useGameStore = create(853+ combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {854+ return {855+ setHistory: (nextHistory) => {856+ set((state) => ({857+ history:858+ typeof nextHistory === 'function'859+ ? nextHistory(state.history)860+ : nextHistory,861+ }))862+ },863+ setXIsNext: (nextXIsNext) => {864+ set((state) => ({865+ xIsNext:866+ typeof nextXIsNext === 'function'867+ ? nextXIsNext(state.xIsNext)868+ : nextXIsNext,869+ }))870+ },871+ }872+ }),873+)874+```875+876+Notice how `[Array(9).fill(null)]` creates an array with a single item, which is itself an array of877+9 null values.878+879+To render the squares for the current move, you'll need to read the most recent squares array from880+the `history` state. You don't need an extra state for this because you already have enough881+information to calculate it during rendering:882+883+```jsx {2-6}884+export default function Game() {885+ const history = useGameStore((state) => state.history)886+ const setHistory = useGameStore((state) => state.setHistory)887+ const xIsNext = useGameStore((state) => state.xIsNext)888+ const setXIsNext = useGameStore((state) => state.setXIsNext)889+ const currentSquares = history[history.length - 1]890+891+ return (892+ <div893+ style={{894+ display: 'flex',895+ flexDirection: 'row',896+ fontFamily: 'monospace',897+ }}898+ >899+ <div>900+ <Board />901+ </div>902+ <div style={{ marginLeft: '1rem' }}>903+ <ol>{/*TODO*/}</ol>904+ </div>905+ </div>906+ )907+}908+```909+910+Next, create a `handlePlay` function inside the `Game` component that will be called by the `Board`911+component to update the game. Pass `xIsNext`, `currentSquares` and `handlePlay` as props to the912+`Board` component:913+914+```jsx {8-10,21}915+export default function Game() {916+ const history = useGameStore((state) => state.history)917+ const setHistory = useGameStore((state) => state.setHistory)918+ const xIsNext = useGameStore((state) => state.xIsNext)919+ const setXIsNext = useGameStore((state) => state.setXIsNext)920+ const currentSquares = history[history.length - 1]921+922+ function handlePlay(nextSquares) {923+ // TODO924+ }925+926+ return (927+ <div928+ style={{929+ display: 'flex',930+ flexDirection: 'row',931+ fontFamily: 'monospace',932+ }}933+ >934+ <div>935+ <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />936+ </div>937+ <div style={{ marginLeft: '1rem' }}>938+ <ol>{/*TODO*/}</ol>939+ </div>940+ </div>941+ )942+}943+```944+945+Let's make the `Board` component fully controlled by the props it receives. To do this, we'll modify946+the `Board` component to accept three props: `xIsNext`, `squares`, and a new `onPlay` function that947+the `Board` component can call with the updated squares array when a player makes a move.948+949+```jsx {1}950+function Board({ xIsNext, squares, onPlay }) {951+ const winner = calculateWinner(squares)952+ const turns = calculateTurns(squares)953+ const player = xIsNext ? 'X' : 'O'954+ const status = calculateStatus(winner, turns, player)955+956+ function handleClick(i) {957+ if (squares[i] || winner) return958+ const nextSquares = squares.slice()959+ nextSquares[i] = player960+ onPlay(nextSquares)961+ }962+963+ return (964+ <>965+ <div style={{ marginBottom: '0.5rem' }}>{status}</div>966+ <div967+ style={{968+ display: 'grid',969+ gridTemplateColumns: 'repeat(3, 1fr)',970+ gridTemplateRows: 'repeat(3, 1fr)',971+ width: 'calc(3 * 2.5rem)',972+ height: 'calc(3 * 2.5rem)',973+ border: '1px solid #999',974+ }}975+ >976+ {squares.map((square, squareIndex) => (977+ <Square978+ key={squareIndex}979+ value={square}980+ onSquareClick={() => handleClick(squareIndex)}981+ />982+ ))}983+ </div>984+ </>985+ )986+}987+```988+989+The `Board` component is now fully controlled by the props passed to it by the `Game` component. To990+get the game working again, you need to implement the `handlePlay` function in the `Game`991+component.992+993+What should `handlePlay` do when called? Previously, the `Board` component called `setSquares` with994+an updated array; now it passes the updated squares array to `onPlay`.995+996+The `handlePlay` function needs to update the `Game` component's state to trigger a re-render.997+Instead of using `setSquares`, you'll update the `history` state variable by appending the updated998+squares array as a new `history` entry. You also need to toggle `xIsNext`, just as the `Board`999+component used1000+to do.1001+1002+```js {2-3}1003+function handlePlay(nextSquares) {1004+ setHistory(history.concat([nextSquares]))1005+ setXIsNext(!xIsNext)1006+}1007+```1008+1009+At this point, you've moved the state to live in the `Game` component, and the UI should be fully1010+working, just as it was before the refactor. Here is what the code should look like at this point:1011+1012+```jsx1013+import { create } from 'zustand'1014+import { combine } from 'zustand/middleware'1015+1016+const useGameStore = create(1017+ combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {1018+ return {1019+ setHistory: (nextHistory) => {1020+ set((state) => ({1021+ history:1022+ typeof nextHistory === 'function'1023+ ? nextHistory(state.history)1024+ : nextHistory,1025+ }))1026+ },1027+ setXIsNext: (nextXIsNext) => {1028+ set((state) => ({1029+ xIsNext:1030+ typeof nextXIsNext === 'function'1031+ ? nextXIsNext(state.xIsNext)1032+ : nextXIsNext,1033+ }))1034+ },1035+ }1036+ }),1037+)1038+1039+function Square({ value, onSquareClick }) {1040+ return (1041+ <button1042+ style={{1043+ display: 'inline-flex',1044+ alignItems: 'center',1045+ justifyContent: 'center',1046+ padding: 0,1047+ backgroundColor: '#fff',1048+ border: '1px solid #999',1049+ outline: 0,1050+ borderRadius: 0,1051+ fontSize: '1rem',1052+ fontWeight: 'bold',1053+ }}1054+ onClick={onSquareClick}1055+ >1056+ {value}1057+ </button>1058+ )1059+}1060+1061+function Board({ xIsNext, squares, onPlay }) {1062+ const winner = calculateWinner(squares)1063+ const turns = calculateTurns(squares)1064+ const player = xIsNext ? 'X' : 'O'1065+ const status = calculateStatus(winner, turns, player)1066+1067+ function handleClick(i) {1068+ if (squares[i] || winner) return1069+ const nextSquares = squares.slice()1070+ nextSquares[i] = player1071+ onPlay(nextSquares)1072+ }1073+1074+ return (1075+ <>1076+ <div style={{ marginBottom: '0.5rem' }}>{status}</div>1077+ <div1078+ style={{1079+ display: 'grid',1080+ gridTemplateColumns: 'repeat(3, 1fr)',1081+ gridTemplateRows: 'repeat(3, 1fr)',1082+ width: 'calc(3 * 2.5rem)',1083+ height: 'calc(3 * 2.5rem)',1084+ border: '1px solid #999',1085+ }}1086+ >1087+ {squares.map((square, squareIndex) => (1088+ <Square1089+ key={squareIndex}1090+ value={square}1091+ onSquareClick={() => handleClick(squareIndex)}1092+ />1093+ ))}1094+ </div>1095+ </>1096+ )1097+}1098+1099+export default function Game() {1100+ const history = useGameStore((state) => state.history)1101+ const setHistory = useGameStore((state) => state.setHistory)1102+ const xIsNext = useGameStore((state) => state.xIsNext)1103+ const setXIsNext = useGameStore((state) => state.setXIsNext)1104+ const currentSquares = history[history.length - 1]1105+1106+ function handlePlay(nextSquares) {1107+ setHistory(history.concat([nextSquares]))1108+ setXIsNext(!xIsNext)1109+ }1110+1111+ return (1112+ <div1113+ style={{1114+ display: 'flex',1115+ flexDirection: 'row',1116+ fontFamily: 'monospace',1117+ }}1118+ >1119+ <div>1120+ <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1121+ </div>1122+ <div style={{ marginLeft: '1rem' }}>1123+ <ol>{/*TODO*/}</ol>1124+ </div>1125+ </div>1126+ )1127+}1128+1129+function calculateWinner(squares) {1130+ const lines = [1131+ [0, 1, 2],1132+ [3, 4, 5],1133+ [6, 7, 8],1134+ [0, 3, 6],1135+ [1, 4, 7],1136+ [2, 5, 8],1137+ [0, 4, 8],1138+ [2, 4, 6],1139+ ]1140+1141+ for (let i = 0; i < lines.length; i++) {1142+ const [a, b, c] = lines[i]1143+ if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {1144+ return squares[a]1145+ }1146+ }1147+1148+ return null1149+}1150+1151+function calculateTurns(squares) {1152+ return squares.filter((square) => !square).length1153+}1154+1155+function calculateStatus(winner, turns, player) {1156+ if (!winner && !turns) return 'Draw'1157+ if (winner) return `Winner ${winner}`1158+ return `Next player: ${player}`1159+}1160+```1161+1162+### Showing the past moves1163+1164+Since you are recording the tic-tac-toe game's history, you can now display a list of past moves to1165+the player.1166+1167+You already have an array of `history` moves in store, so now you need to transform it to an array1168+of React elements. In JavaScript, to transform one array into another, you can use the Array1169+`.map()` method:1170+1171+You'll use `map` to transform your `history` of moves into React elements representing buttons on the1172+screen, and display a list of buttons to **jump** to past moves. Let's `map` over the `history` in1173+the `Game` component:1174+1175+```jsx {29-44}1176+export default function Game() {1177+ const history = useGameStore((state) => state.history)1178+ const setHistory = useGameStore((state) => state.setHistory)1179+ const xIsNext = useGameStore((state) => state.xIsNext)1180+ const setXIsNext = useGameStore((state) => state.setXIsNext)1181+ const currentSquares = history[history.length - 1]1182+1183+ function handlePlay(nextSquares) {1184+ setHistory(history.concat([nextSquares]))1185+ setXIsNext(!xIsNext)1186+ }1187+1188+ function jumpTo(nextMove) {1189+ // TODO1190+ }1191+1192+ return (1193+ <div1194+ style={{1195+ display: 'flex',1196+ flexDirection: 'row',1197+ fontFamily: 'monospace',1198+ }}1199+ >1200+ <div>1201+ <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1202+ </div>1203+ <div style={{ marginLeft: '1rem' }}>1204+ <ol>1205+ {history.map((_, historyIndex) => {1206+ const description =1207+ historyIndex > 01208+ ? `Go to move #${historyIndex}`1209+ : 'Go to game start'1210+1211+ return (1212+ <li key={historyIndex}>1213+ <button onClick={() => jumpTo(historyIndex)}>1214+ {description}1215+ </button>1216+ </li>1217+ )1218+ })}1219+ </ol>1220+ </div>1221+ </div>1222+ )1223+}1224+```1225+1226+Before you can implement the `jumpTo` function, you need the `Game` component to keep track of which1227+step the user is currently viewing. To do this, define a new state variable called `currentMove`,1228+which will start at `0`:1229+1230+```js {3,14-21}1231+const useGameStore = create(1232+ combine(1233+ { history: [Array(9).fill(null)], currentMove: 0, xIsNext: true },1234+ (set) => {1235+ return {1236+ setHistory: (nextHistory) => {1237+ set((state) => ({1238+ history:1239+ typeof nextHistory === 'function'1240+ ? nextHistory(state.history)1241+ : nextHistory,1242+ }))1243+ },1244+ setCurrentMove: (nextCurrentMove) => {1245+ set((state) => ({1246+ currentMove:1247+ typeof nextCurrentMove === 'function'1248+ ? nextCurrentMove(state.currentMove)1249+ : nextCurrentMove,1250+ }))1251+ },1252+ setXIsNext: (nextXIsNext) => {1253+ set((state) => ({1254+ xIsNext:1255+ typeof nextXIsNext === 'function'1256+ ? nextXIsNext(state.xIsNext)1257+ : nextXIsNext,1258+ }))1259+ },1260+ }1261+ },1262+ ),1263+)1264+```1265+1266+Next, update the `jumpTo` function inside `Game` component to update that `currentMove`. You’ll1267+also set `xIsNext` to `true` if the number that you’re changing `currentMove` to is even.1268+1269+```js {2-3}1270+function jumpTo(nextMove) {1271+ setCurrentMove(nextMove)1272+ setXIsNext(currentMove % 2 === 0)1273+}1274+```1275+1276+You will now make two changes to the `handlePlay` function in the `Game` component, which is called1277+when you click on a square.1278+1279+- If you "go back in time" and then make a new move from that point, you only want to keep the1280+ history up to that point. Instead of adding `nextSquares` after all items in the history (using1281+ the Array `.concat()` method), you'll add it after all items in1282+ `history.slice(0, currentMove + 1)` to keep only that portion of the old history.1283+- Each time a move is made, you need to update `currentMove` to point to the latest history entry.1284+1285+```js {2-4}1286+function handlePlay(nextSquares) {1287+ const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1288+ setHistory(nextHistory)1289+ setCurrentMove(nextHistory.length - 1)1290+ setXIsNext(!xIsNext)1291+}1292+```1293+1294+Finally, you will modify the `Game` component to render the currently selected move, instead of1295+always rendering the final move:1296+1297+```jsx {2-8}1298+export default function Game() {1299+ const history = useGameStore((state) => state.history)1300+ const setHistory = useGameStore((state) => state.setHistory)1301+ const currentMove = useGameStore((state) => state.currentMove)1302+ const setCurrentMove = useGameStore((state) => state.setCurrentMove)1303+ const xIsNext = useGameStore((state) => state.xIsNext)1304+ const setXIsNext = useGameStore((state) => state.setXIsNext)1305+ const currentSquares = history[currentMove]1306+1307+ function handlePlay(nextSquares) {1308+ const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1309+ setHistory(nextHistory)1310+ setCurrentMove(nextHistory.length - 1)1311+ setXIsNext(!xIsNext)1312+ }1313+1314+ function jumpTo(nextMove) {1315+ setCurrentMove(nextMove)1316+ setXIsNext(nextMove % 2 === 0)1317+ }1318+1319+ return (1320+ <div1321+ style={{1322+ display: 'flex',1323+ flexDirection: 'row',1324+ fontFamily: 'monospace',1325+ }}1326+ >1327+ <div>1328+ <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1329+ </div>1330+ <div style={{ marginLeft: '1rem' }}>1331+ <ol>1332+ {history.map((_, historyIndex) => {1333+ const description =1334+ historyIndex > 01335+ ? `Go to move #${historyIndex}`1336+ : 'Go to game start'1337+1338+ return (1339+ <li key={historyIndex}>1340+ <button onClick={() => jumpTo(historyIndex)}>1341+ {description}1342+ </button>1343+ </li>1344+ )1345+ })}1346+ </ol>1347+ </div>1348+ </div>1349+ )1350+}1351+```1352+1353+### Final cleanup1354+1355+If you look closely at the code, you'll see that `xIsNext` is `true` when `currentMove` is even and1356+`false` when `currentMove` is odd. This means that if you know the value of `currentMove`, you can1357+always determine what `xIsNext` should be.1358+1359+There's no need to store `xIsNext` separately in the state. It’s better to avoid redundant state1360+because it can reduce bugs and make your code easier to understand. Instead, you can calculate1361+`xIsNext` based on `currentMove`:1362+1363+```jsx {2-5,13,17}1364+export default function Game() {1365+ const history = useGameStore((state) => state.history)1366+ const setHistory = useGameStore((state) => state.setHistory)1367+ const currentMove = useGameStore((state) => state.currentMove)1368+ const setCurrentMove = useGameStore((state) => state.setCurrentMove)1369+ const xIsNext = currentMove % 2 === 01370+ const currentSquares = history[currentMove]1371+1372+ function handlePlay(nextSquares) {1373+ const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])1374+ setHistory(nextHistory)1375+ setCurrentMove(nextHistory.length - 1)1376+ }1377+1378+ function jumpTo(nextMove) {1379+ setCurrentMove(nextMove)1380+ }1381+1382+ return (1383+ <div1384+ style={{1385+ display: 'flex',1386+ flexDirection: 'row',1387+ fontFamily: 'monospace',1388+ }}1389+ >1390+ <div>1391+ <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />1392+ </div>1393+ <div style={{ marginLeft: '1rem' }}>1394+ <ol>1395+ {history.map((_, historyIndex) => {1396+ const description =1397+ historyIndex > 01398+ ? `Go to move #${historyIndex}`1399+ : 'Go to game start'1400+1401+ return (1402+ <li key={historyIndex}>1403+ <button onClick={() => jumpTo(historyIndex)}>1404+ {description}1405+ </button>1406+ </li>1407+ )1408+ })}1409+ </ol>1410+ </div>1411+ </div>1412+ )1413+}1414+```1415+1416+You no longer need the `xIsNext` state declaration or the calls to `setXIsNext`. Now, there’s no1417+chance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding1418+the components.1419+1420+### Wrapping up1421+1422+Congratulations! You’ve created a tic-tac-toe game that:1423+1424+- Lets you play tic-tac-toe,1425+- Indicates when a player has won the game or when is drawn,1426+- Stores a game’s history as a game progresses,1427+- Allows players to review a game’s history and see previous versions of a game’s board.1428+1429+Nice work! We hope you now feel like you have a decent grasp of how React and Zustand works.added:docs/learn/guides/updating-state.md+141 added
1+---2+title: Updating state3+nav: 44+---5+6+## Flat updates7+8+Updating state with Zustand is simple! Call the provided `set` function with9+the new state, and it will be shallowly merged with the existing state in the10+store. **Note** See next section for nested state.11+12+```tsx13+import { create } from 'zustand'14+15+type State = {16+ firstName: string17+ lastName: string18+}19+20+type Action = {21+ updateFirstName: (firstName: State['firstName']) => void22+ updateLastName: (lastName: State['lastName']) => void23+}24+25+// Create your store, which includes both state and (optionally) actions26+const usePersonStore = create<State & Action>((set) => ({27+ firstName: '',28+ lastName: '',29+ updateFirstName: (firstName) => set(() => ({ firstName: firstName })),30+ updateLastName: (lastName) => set(() => ({ lastName: lastName })),31+}))32+33+// In consuming app34+function App() {35+ // "select" the needed state and actions, in this case, the firstName value36+ // and the action updateFirstName37+ const firstName = usePersonStore((state) => state.firstName)38+ const updateFirstName = usePersonStore((state) => state.updateFirstName)39+40+ return (41+ <main>42+ <label>43+ First name44+ <input45+ // Update the "firstName" state46+ onChange={(e) => updateFirstName(e.currentTarget.value)}47+ value={firstName}48+ />49+ </label>50+51+ <p>52+ Hello, <strong>{firstName}!</strong>53+ </p>54+ </main>55+ )56+}57+```58+59+## Deeply nested object60+61+If you have a deep state object like this:62+63+```ts64+type State = {65+ deep: {66+ nested: {67+ obj: { count: number }68+ }69+ }70+}71+```72+73+Updating nested state requires some effort to ensure the process is completed74+immutably.75+76+### Normal approach77+78+Similar to React or Redux, the normal approach is to copy each level of the79+state object. This is done with the spread operator `...`, and by manually80+merging that in with the new state values. Like so:81+82+```ts83+ normalInc: () =>84+ set((state) => ({85+ deep: {86+ ...state.deep,87+ nested: {88+ ...state.deep.nested,89+ obj: {90+ ...state.deep.nested.obj,91+ count: state.deep.nested.obj.count + 192+ }93+ }94+ }95+ })),96+```97+98+This is very long! Let's explore some alternatives that will make your life99+easier.100+101+### With Immer102+103+Many people use [Immer](https://github.com/immerjs/immer) to update nested104+values. Immer can be used anytime you need to update nested state such as in105+React, Redux and of course, Zustand!106+107+You can use Immer to shorten your state updates for deeply nested object. Let's108+take a look at an example:109+110+```ts111+ immerInc: () =>112+ set(produce((state: State) => { ++state.deep.nested.obj.count })),113+```114+115+What a reduction! Please take note of the [gotchas listed here](../../reference/integrations/immer-middleware.md).116+117+### With optics-ts118+119+There is another option with [optics-ts](https://github.com/akheron/optics-ts/):120+121+```ts122+ opticsInc: () =>123+ set(O.modify(O.optic<State>().path("deep.nested.obj.count"))((c) => c + 1)),124+```125+126+Unlike Immer, optics-ts doesn't use proxies or mutation syntax.127+128+### With Ramda129+130+You can also use [Ramda](https://ramdajs.com/):131+132+```ts133+ ramdaInc: () =>134+ set(R.modifyPath(["deep", "nested", "obj", "count"], (c) => c + 1)),135+```136+137+Both ramda and optics-ts also work with types.138+139+### Demo140+141+https://stackblitz.com/edit/vitejs-vite-j6bjdyguadded:docs/learn/index.md+54 added
1+---2+title: Learn3+description: A guided path to understand Zustand fundamentals, common patterns, and when to reach for specific tools.4+---5+6+## Start here7+8+If you are new to Zustand, begin here for installation, a high-level overview, and a hands-on tutorial.9+10+- [Introduction](/learn/getting-started/introduction.md) — Install Zustand and create your first store.11+- [Comparison with other tools](/learn/getting-started/comparison.md) — See how Zustand compares to Redux, Jotai, Recoil, and others.12+- [Tutorial: Tic Tac Toe](/learn/guides/tutorial-tic-tac-toe.md) — Build a complete game to learn Zustand concepts step by step.13+14+## Core concepts15+16+The fundamentals of reading and updating state in a Zustand store.17+18+- [Updating state](/learn/guides/updating-state.md) — How to update primitive values, objects, and nested state.19+- [Practice with no store actions](/learn/guides/practice-with-no-store-actions.md) — Define state updates outside the store for simpler patterns.20+- [Slices pattern](/learn/guides/slices-pattern.md) — Split a large store into smaller, composable slices.21+- [Immutable state and merging](/learn/guides/immutable-state-and-merging.md) — Understand how Zustand merges state and when to spread manually.22+- [Maps and sets usage](/learn/guides/maps-and-sets-usage.md) — Work with `Map` and `Set` inside Zustand state correctly.23+24+## Performance and rendering25+26+Techniques for keeping re-renders minimal and components fast.27+28+- [Prevent rerenders with useShallow](/learn/guides/prevent-rerenders-with-use-shallow.md) — Use shallow comparison to avoid unnecessary re-renders when selecting objects.29+- [Connect to state with URL hash](/learn/guides/connect-to-state-with-url-hash.md) — Sync store state with the URL hash for shareable UI state.30+- [Event handler in pre React 18](/learn/guides/event-handler-in-pre-react-18.md) — Handle the batching edge case in React 17 and earlier.31+32+## TypeScript path33+34+Guides for typing stores, actions, and selectors with TypeScript.35+36+- [Beginner TypeScript](/learn/guides/beginner-typescript.md) — Type a basic store with state and actions.37+- [Advanced TypeScript](/learn/guides/advanced-typescript.md) — Type slices, middleware stacks, and complex patterns.38+- [Auto-generating selectors](/learn/guides/auto-generating-selectors.md) — Generate typed selectors automatically from a store definition.39+40+## Frameworks and platforms41+42+Using Zustand in server-rendered and framework-specific environments.43+44+- [Next.js](/learn/guides/nextjs.md) — Set up Zustand in a Next.js app with proper SSR handling.45+- [SSR and hydration](/learn/guides/ssr-and-hydration.md) — Avoid hydration mismatches when rendering on the server.46+- [Initialize state with props](/learn/guides/initialize-state-with-props.md) — Seed a store's initial state from React component props.47+48+## Testing and quality49+50+Best practices for writing reliable, maintainable code with Zustand.51+52+- [Testing stores and components](/learn/guides/testing.md) — Test store logic and React components that consume a store.53+- [Flux-inspired practice](/learn/guides/flux-inspired-practice.md) — Apply Flux conventions to keep state changes predictable.54+- [How to reset state](/learn/guides/how-to-reset-state.md) — Reset a store back to its initial state on demand.deleted:docs/middlewares/combine.md-103 removed
1----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'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-TBDdeleted:docs/middlewares/devtools.md-352 removed
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/reduxjs/redux-devtools)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-> [!IMPORTANT]13-> In order to use `devtools` from `zustand/middleware` you need to install14-> `@redux-devtools/extension` library.15-16-```js17-const nextStateCreatorFn = devtools(stateCreatorFn, devtoolsOptions)18-```19-20-- [Types](#types)21- - [Signature](#signature)22- - [Mutator](#mutator)23-- [Reference](#reference)24-- [Usage](#usage)25- - [Debugging a store](#debugging-a-store)26- - [Debugging a Slices pattern based store](#debugging-a-slices-pattern-based-store)27- - [Filtering actions with actionsDenylist](#filtering-actions-with-actionsdenylist)28- - [Cleanup](#cleanup)29-- [Troubleshooting](#troubleshooting)30- - [Only one store is displayed](#only-one-store-is-displayed)31- - [Action names are labeled as 'anonymous'](#all-action-names-are-labeled-as-anonymous)32-33-## Types34-35-### Signature36-37-```ts38-devtools<T>(stateCreatorFn: StateCreator<T, [], []>, devtoolsOptions?: DevtoolsOptions): StateCreator<T, [['zustand/devtools', never]], []>39-```40-41-### Mutator42-43-<!-- prettier-ignore-start -->44-```ts45-['zustand/devtools', never]46-```47-<!-- prettier-ignore-end -->48-49-## Reference50-51-### `devtools(stateCreatorFn, devtoolsOptions)`52-53-#### Parameters54-55-- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.56- Usually, you will return an object with the methods you want to expose.57-- **optional** `devtoolsOptions`: An object to define `Redux Devtools` options.58- - **optional** `name`: A custom identifier for the connection in the Redux DevTools.59- - **optional** `enabled`: Defaults to `true` when is on development mode, and defaults to `false`60- when is on production mode. Enables or disables the Redux DevTools integration61- for this store.62- - **optional** `anonymousActionType`: Defaults to the inferred action type or `anonymous` if63- unavailable. A string to use as the action type for anonymous mutations in the Redux DevTools.64- - **optional** `store`: A custom identifier for the store in the Redux DevTools.65- - **optional** `actionsDenylist`: A string or array of strings (regex patterns) that specify which66- actions should be filtered out from Redux DevTools. This option is passed directly to Redux DevTools67- for filtering. For example, `['secret.*']` will filter out all actions starting with "secret".68-69-#### Returns70-71-`devtools` returns a state creator function.72-73-## Usage74-75-### Debugging a store76-77-This example shows you how you can use `Redux Devtools` to debug a store78-79-```ts80-import { create, StateCreator } from 'zustand'81-import { devtools } from 'zustand/middleware'82-83-type JungleStore = {84- bears: number85- addBear: () => void86- fishes: number87- addFish: () => void88-}89-90-const useJungleStore = create<JungleStore>()(91- devtools((set) => ({92- bears: 0,93- addBear: () =>94- set((state) => ({ bears: state.bears + 1 }), undefined, 'jungle/addBear'),95- fishes: 0,96- addFish: () =>97- set(98- (state) => ({ fishes: state.fishes + 1 }),99- undefined,100- 'jungle/addFish',101- ),102- })),103-)104-```105-106-### Debugging a Slices pattern based store107-108-This example shows you how you can use `Redux Devtools` to debug a Slices pattern based store109-110-```ts111-import { create, StateCreator } from 'zustand'112-import { devtools } from 'zustand/middleware'113-114-type BearSlice = {115- bears: number116- addBear: () => void117-}118-119-type FishSlice = {120- fishes: number121- addFish: () => void122-}123-124-type JungleStore = BearSlice & FishSlice125-126-const createBearSlice: StateCreator<127- JungleStore,128- [['zustand/devtools', never]],129- [],130- BearSlice131-> = (set) => ({132- bears: 0,133- addBear: () =>134- set(135- (state) => ({ bears: state.bears + 1 }),136- undefined,137- 'jungle:bear/addBear',138- ),139-})140-141-const createFishSlice: StateCreator<142- JungleStore,143- [['zustand/devtools', never]],144- [],145- FishSlice146-> = (set) => ({147- fishes: 0,148- addFish: () =>149- set(150- (state) => ({ fishes: state.fishes + 1 }),151- undefined,152- 'jungle:fish/addFish',153- ),154-})155-156-const useJungleStore = create<JungleStore>()(157- devtools((...args) => ({158- ...createBearSlice(...args),159- ...createFishSlice(...args),160- })),161-)162-```163-164-### Filtering actions with actionsDenylist165-166-You can filter out specific actions from Redux DevTools using the `actionsDenylist` option. This is useful for hiding internal or sensitive actions from the DevTools timeline.167-168-```ts169-import { create } from 'zustand'170-import { devtools } from 'zustand/middleware'171-172-type Store = {173- user: string | null174- token: string | null175- login: (user: string, token: string) => void176- logout: () => void177- updateData: () => void178-}179-180-const useStore = create<Store>()(181- devtools(182- (set) => ({183- user: null,184- token: null,185- login: (user, token) => set({ user, token }, undefined, 'auth/login'),186- logout: () => set({ user: null, token: null }, undefined, 'auth/logout'),187- updateData: () =>188- set({ user: 'updated' }, undefined, 'internal/updateData'),189- }),190- {191- name: 'AuthStore',192- // Filter out actions matching these regex patterns193- actionsDenylist: ['internal/.*'], // Hides all 'internal/*' actions194- },195- ),196-)197-```198-199-You can also use a single regex string:200-201-```ts202-const useStore = create<Store>()(203- devtools(204- (set) => ({205- // ... state and actions206- }),207- {208- name: 'MyStore',209- actionsDenylist: 'secret.*', // Hides all actions starting with 'secret'210- },211- ),212-)213-```214-215-> [!NOTE]216-> The `actionsDenylist` option uses regex pattern matching and is handled directly by Redux DevTools Extension.217-> All actions are still sent to DevTools, but matching actions are filtered from the display.218-219-### Cleanup220-221-When a store is no longer needed, you can clean up the Redux DevTools connection by calling the `cleanup` method on the store:222-223-```ts224-import { create } from 'zustand'225-import { devtools } from 'zustand/middleware'226-227-const useStore = create(228- devtools((set) => ({229- count: 0,230- increment: () => set((state) => ({ count: state.count + 1 })),231- })),232-)233-234-// When you're done with the store, clean it up235-useStore.devtools.cleanup()236-```237-238-This is particularly useful in applications that wrap store in context or create multiple stores dynamically.239-240-## Troubleshooting241-242-### Only one store is displayed243-244-By default, `Redux Devtools` only show one store at a time, so in order to see other stores you245-need to use store selector and choose a different store.246-247-### All action names are labeled as 'anonymous'248-249-If an action type name is not provided, it is defaulted to "anonymous". You can customize this250-default value by providing a `anonymousActionType` parameter:251-252-For instance the next example doesn't have action type name:253-254-```ts255-import { create, StateCreator } from 'zustand'256-import { devtools } from 'zustand/middleware'257-258-type BearSlice = {259- bears: number260- addBear: () => void261-}262-263-type FishSlice = {264- fishes: number265- addFish: () => void266-}267-268-type JungleStore = BearSlice & FishSlice269-270-const createBearSlice: StateCreator<271- JungleStore,272- [['zustand/devtools', never]],273- [],274- BearSlice275-> = (set) => ({276- bears: 0,277- addBear: () => set((state) => ({ bears: state.bears + 1 })),278- eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),279-})280-281-const createFishSlice: StateCreator<282- JungleStore,283- [['zustand/devtools', never]],284- [],285- FishSlice286-> = (set) => ({287- fishes: 0,288- addFish: () => set((state) => ({ fishes: state.fishes + 1 })),289-})290-291-const useJungleStore = create<JungleStore>()(292- devtools((...args) => ({293- ...createBearSlice(...args),294- ...createFishSlice(...args),295- })),296-)297-```298-299-In order to fix the previous example, we need to provide an action type name as the third parameter.300-Additionally, to preserve the default behavior of the replacement logic, the second parameter301-should be set to `undefined`.302-303-Here's the fixed previous example304-305-```ts306-import { create, StateCreator } from 'zustand'307-308-type BearSlice = {309- bears: number310- addBear: () => void311-}312-313-type FishSlice = {314- fishes: number315- addFish: () => void316-}317-318-type JungleStore = BearSlice & FishSlice319-320-const createBearSlice: StateCreator<321- JungleStore,322- [['zustand/devtools', never]],323- [],324- BearSlice325-> = (set) => ({326- bears: 0,327- addBear: () =>328- set((state) => ({ bears: state.bears + 1 }), undefined, 'bear/addBear'),329-})330-331-const createFishSlice: StateCreator<332- JungleStore,333- [['zustand/devtools', never]],334- [],335- FishSlice336-> = (set) => ({337- fishes: 0,338- addFish: () =>339- set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fish/addFish'),340-})341-342-const useJungleStore = create<JungleStore>()(343- devtools((...args) => ({344- ...createBearSlice(...args),345- ...createFishSlice(...args),346- })),347-)348-```349-350-> [!IMPORTANT]351-> Do not set the second parameter to `true` or `false` unless you want to override the default352-> replacement logicdeleted:docs/middlewares/immer.md-239 removed
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-> [!IMPORTANT]12-> In order to use `immer` from `zustand/middleware/immer` you need to install13-> `immer` library.14-15-```js16-const nextStateCreatorFn = immer(stateCreatorFn)17-```18-19-- [Types](#types)20- - [Signature](#signature)21- - [Mutator](#mutator)22-- [Reference](#reference)23-- [Usage](#usage)24-- [Troubleshooting](#troubleshooting)25-26-## Types27-28-### Signature29-30-```ts31-immer<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/immer', never]], []>32-```33-34-### Mutator35-36-<!-- prettier-ignore-start -->37-```ts38-['zustand/immer', never]39-```40-<!-- prettier-ignore-end -->41-42-## Reference43-44-### `immer(stateCreatorFn)`45-46-#### Parameters47-48-- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.49- Usually, you will return an object with the methods you want to expose.50-51-#### Returns52-53-`immer` returns a state creator function.54-55-## Usage56-57-### Updating state without boilerplate code58-59-In the next example, we're going to update the `person` object. Since it's a nested object, we need60-to create a copy of the entire object before making the update.61-62-```ts63-import { createStore } from 'zustand/vanilla'64-65-type PersonStoreState = {66- person: { firstName: string; lastName: string; email: string }67-}68-69-type PersonStoreActions = {70- setPerson: (71- nextPerson: (72- person: PersonStoreState['person'],73- ) => PersonStoreState['person'] | PersonStoreState['person'],74- ) => void75-}76-77-type PersonStore = PersonStoreState & PersonStoreActions78-79-const personStore = createStore<PersonStore>()((set) => ({80- person: {81- firstName: 'Barbara',82- lastName: 'Hepworth',83- email: 'bhepworth@sculpture.com',84- },85- setPerson: (nextPerson) =>86- set((state) => ({87- person:88- typeof nextPerson === 'function'89- ? nextPerson(state.person)90- : nextPerson,91- })),92-}))93-94-const $firstNameInput = document.getElementById(95- 'first-name',96-) as HTMLInputElement97-const $lastNameInput = document.getElementById('last-name') as HTMLInputElement98-const $emailInput = document.getElementById('email') as HTMLInputElement99-const $result = document.getElementById('result') as HTMLDivElement100-101-function handleFirstNameChange(event: Event) {102- personStore.getState().setPerson((person) => ({103- ...person,104- firstName: (event.target as any).value,105- }))106-}107-108-function handleLastNameChange(event: Event) {109- personStore.getState().setPerson((person) => ({110- ...person,111- lastName: (event.target as any).value,112- }))113-}114-115-function handleEmailChange(event: Event) {116- personStore.getState().setPerson((person) => ({117- ...person,118- email: (event.target as any).value,119- }))120-}121-122-$firstNameInput.addEventListener('input', handleFirstNameChange)123-$lastNameInput.addEventListener('input', handleLastNameChange)124-$emailInput.addEventListener('input', handleEmailChange)125-126-const render: Parameters<typeof personStore.subscribe>[0] = (state) => {127- $firstNameInput.value = state.person.firstName128- $lastNameInput.value = state.person.lastName129- $emailInput.value = state.person.email130-131- $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`132-}133-134-render(personStore.getInitialState(), personStore.getInitialState())135-136-personStore.subscribe(render)137-```138-139-Here's the `html` code140-141-```html142-<label style="display: block">143- First name:144- <input id="first-name" />145-</label>146-<label style="display: block">147- Last name:148- <input id="last-name" />149-</label>150-<label style="display: block">151- Email:152- <input id="email" />153-</label>154-<p id="result"></p>155-```156-157-To avoid manually copying the entire object before making updates, we'll use the `immer`158-middleware.159-160-```ts161-import { createStore } from 'zustand/vanilla'162-import { immer } from 'zustand/middleware/immer'163-164-type PersonStoreState = {165- person: { firstName: string; lastName: string; email: string }166-}167-168-type PersonStoreActions = {169- setPerson: (170- nextPerson: (171- person: PersonStoreState['person'],172- ) => PersonStoreState['person'] | PersonStoreState['person'],173- ) => void174-}175-176-type PersonStore = PersonStoreState & PersonStoreActions177-178-const personStore = createStore<PersonStore>()(179- immer((set) => ({180- person: {181- firstName: 'Barbara',182- lastName: 'Hepworth',183- email: 'bhepworth@sculpture.com',184- },185- setPerson: (nextPerson) =>186- set((state) => {187- state.person =188- typeof nextPerson === 'function'189- ? nextPerson(state.person)190- : nextPerson191- }),192- })),193-)194-195-const $firstNameInput = document.getElementById(196- 'first-name',197-) as HTMLInputElement198-const $lastNameInput = document.getElementById('last-name') as HTMLInputElement199-const $emailInput = document.getElementById('email') as HTMLInputElement200-const $result = document.getElementById('result') as HTMLDivElement201-202-function handleFirstNameChange(event: Event) {203- personStore.getState().setPerson((person) => {204- person.firstName = (event.target as any).value205- })206-}207-208-function handleLastNameChange(event: Event) {209- personStore.getState().setPerson((person) => {210- person.lastName = (event.target as any).value211- })212-}213-214-function handleEmailChange(event: Event) {215- personStore.getState().setPerson((person) => {216- person.email = (event.target as any).value217- })218-}219-220-$firstNameInput.addEventListener('input', handleFirstNameChange)221-$lastNameInput.addEventListener('input', handleLastNameChange)222-$emailInput.addEventListener('input', handleEmailChange)223-224-const render: Parameters<typeof personStore.subscribe>[0] = (state) => {225- $firstNameInput.value = state.person.firstName226- $lastNameInput.value = state.person.lastName227- $emailInput.value = state.person.email228-229- $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`230-}231-232-render(personStore.getInitialState(), personStore.getInitialState())233-234-personStore.subscribe(render)235-```236-237-## Troubleshooting238-239-TBDdeleted:docs/middlewares/persist.md-988 removed
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-TBDdeleted:docs/middlewares/redux.md-172 removed
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'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 & {74- dispatch: (action: PersonStoreAction) => PersonStoreAction75-}76-77-const personStoreReducer = (78- state: PersonStoreState,79- action: PersonStoreAction,80-) => {81- switch (action.type) {82- case 'person/setFirstName': {83- return { ...state, firstName: action.firstName }84- }85- case 'person/setLastName': {86- return { ...state, lastName: action.lastName }87- }88- case 'person/setEmail': {89- return { ...state, email: action.email }90- }91- default: {92- return state93- }94- }95-}96-97-const personStoreInitialState: PersonStoreState = {98- firstName: 'Barbara',99- lastName: 'Hepworth',100- email: 'bhepworth@sculpture.com',101-}102-103-const personStore = createStore<PersonStore>()(104- redux(personStoreReducer, personStoreInitialState),105-)106-107-const $firstNameInput = document.getElementById(108- 'first-name',109-) as HTMLInputElement110-const $lastNameInput = document.getElementById('last-name') as HTMLInputElement111-const $emailInput = document.getElementById('email') as HTMLInputElement112-const $result = document.getElementById('result') as HTMLDivElement113-114-function handleFirstNameChange(event: Event) {115- personStore.dispatch({116- type: 'person/setFirstName',117- firstName: (event.target as any).value,118- })119-}120-121-function handleLastNameChange(event: Event) {122- personStore.dispatch({123- type: 'person/setLastName',124- lastName: (event.target as any).value,125- })126-}127-128-function handleEmailChange(event: Event) {129- personStore.dispatch({130- type: 'person/setEmail',131- email: (event.target as any).value,132- })133-}134-135-$firstNameInput.addEventListener('input', handleFirstNameChange)136-$lastNameInput.addEventListener('input', handleLastNameChange)137-$emailInput.addEventListener('input', handleEmailChange)138-139-const render: Parameters<typeof personStore.subscribe>[0] = (person) => {140- $firstNameInput.value = person.firstName141- $lastNameInput.value = person.lastName142- $emailInput.value = person.email143-144- $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`145-}146-147-render(personStore.getInitialState(), personStore.getInitialState())148-149-personStore.subscribe(render)150-```151-152-Here's the `html` code153-154-```html155-<label style="display: block">156- First name:157- <input id="first-name" />158-</label>159-<label style="display: block">160- Last name:161- <input id="last-name" />162-</label>163-<label style="display: block">164- Email:165- <input id="email" />166-</label>167-<p id="result"></p>168-```169-170-## Troubleshooting171-172-TBDdeleted:docs/middlewares/subscribe-with-selector.md-121 removed
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'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-TBDdeleted:docs/migrations/migrating-to-v4.md-362 removed
1----2-title: Migrating to v43-nav: 224----5-6-The only breaking changes are in types.7-If you are using Zustand with TypeScript8-or JSDoc type annotations,9-this guide applies.10-Otherwise, no migration is required.11-12-Also, it's recommended to first read13-the new [TypeScript Guide](../guides/advanced-typescript.md),14-so that the migration is easier to understand.15-16-In addition to this migration guide,17-you can also check the18-[diff](https://github.com/pmndrs/zustand/compare/v3.7.2...v4.0.0?short_path=37e5b4c#diff-c21e24854115b390eccde717da83f91feb2d5927a76c1485e5f0fdd0135c2afa)19-of the test files in the Zustand repository from v3 to v4.20-21-## `create`22-23-**Applicable imports**24-25-```ts26-import create from 'zustand'27-import create from 'zustand/vanilla'28-```29-30-**Change**31-32-```diff33-- create:34-- < State35-- , StoreSetState = StoreApi<State>["set"]36-- , StoreGetState = StoreApi<State>["get"]37-- , Store = StoreApi<State>38-- >39-- (f: ...) => ...40-+ create:41-+ { <State>(): (f: ...) => ...42-+ , <State, Mutators>(f: ...) => ...43-+ }44-```45-46-**Migration**47-48-If you are not passing any type parameters to `create`,49-no migration is required.50-51-If you are using a "leaf" middleware like `combine` or `redux`,52-remove all type parameters from `create`.53-54-Else, replace `create<T, ...>(...)` with `create<T>()(...)`.55-56-## `StateCreator`57-58-**Applicable imports**59-60-```ts61-import type { StateCreator } from 'zustand'62-import type { StateCreator } from 'zustand/vanilla'63-```64-65-**Change**66-67-```diff68-- type StateCreator69-- < State70-- , StoreSetState = StoreApi<State>["set"]71-- , StoreGetState = StoreApi<State>["get"]72-- , Store = StoreApi<State>73-- > =74-- ...75-+ type StateCreator76-+ < State77-+ , InMutators extends [StoreMutatorIdentifier, unknown][] = []78-+ , OutMutators extends [StoreMutatorIdentifier, unknown][] = []79-+ , Return = State80-+ > =81-+ ...82-```83-84-**Migration**85-86-If you are using `StateCreator`,87-you are likely authoring a middleware88-or using the "slices" pattern.89-For that check the90-[Authoring middlewares and advanced usage](../guides/advanced-typescript.md#authoring-middlewares-and-advanced-usage)91-and [Common recipes](../guides/advanced-typescript.md#common-recipes)92-sections of the TypeScript Guide.93-94-## `PartialState`95-96-**Applicable imports**97-98-```ts99-import type { PartialState } from 'zustand'100-import type { PartialState } from 'zustand/vanilla'101-```102-103-**Change**104-105-```diff106-- type PartialState107-- < T extends State108-- , K1 extends keyof T = keyof T109-- , K2 extends keyof T = K1110-- , K3 extends keyof T = K2111-- , K4 extends keyof T = K3112-- > =113-- | (Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)114-- | ((state: T) => Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)115-+ type PartialState<T> =116-+ | Partial<T>117-+ | ((state: T) => Partial<T>)118-```119-120-**Migration**121-122-Replace `PartialState<T, ...>` with `PartialState<T>`123-and preferably turn on [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes)124-in your `tsconfig.json`:125-126-```json127-{128- "compilerOptions": {129- "exactOptionalPropertyTypes": true130- }131-}132-```133-134-We're no longer using the trick to disallow `{ foo: undefined }`135-to be assigned to `Partial<{ foo: string }>`.136-Instead, we're relying on the users to turn on `exactOptionalPropertyTypes`.137-138-## `useStore`139-140-**Applicable imports**141-142-```ts143-import { useStore } from 'zustand'144-import { useStore } from 'zustand/react'145-```146-147-**Change**148-149-```diff150-- useStore:151-- { <State>(store: StoreApi<State>): State152-- , <State, StateSlice>153-- ( store: StoreApi<State>154-- , selector: StateSelector<State, StateSlice>,155-- , equals?: EqualityChecker<StateSlice>156-- ): StateSlice157-- }158-+ useStore:159-+ <Store, StateSlice = ExtractState<Store>>160-+ ( store: Store161-+ , selector?: StateSelector<State, StateSlice>,162-+ , equals?: EqualityChecker<StateSlice>163-+ )164-+ => StateSlice165-```166-167-**Migration**168-169-If you are not passing any type parameters to `useStore`,170-no migration is required.171-172-If you are,173-it's recommended to remove all the type parameters,174-or pass the **store** type instead of the **state** type as the first parameter.175-176-## `UseBoundStore`177-178-**Applicable imports**179-180-```ts181-import type { UseBoundStore } from 'zustand'182-import type { UseBoundStore } from 'zustand/react'183-```184-185-**Change**186-187-```diff188-- type UseBoundStore<189-- State,190-- Store = StoreApi<State>191-- > =192-- & { (): T193-- , <StateSlice>194-- ( selector: StateSelector<State, StateSlice>195-- , equals?: EqualityChecker<StateSlice>196-- ): U197-- }198-- & Store199-+ type UseBoundStore<Store> =200-+ & (<StateSlice = ExtractState<S>>201-+ ( selector?: (state: ExtractState<S>) => StateSlice202-+ , equals?: (a: StateSlice, b: StateSlice) => boolean203-+ ) => StateSlice204-+ )205-+ & S206-```207-208-**Migration**209-210-Replace `UseBoundStore<T>` with `UseBoundStore<StoreApi<T>>`,211-and `UseBoundStore<T, S>` with `UseBoundStore<S>`212-213-## `UseContextStore`214-215-**Applicable imports**216-217-```ts218-import type { UseContextStore } from 'zustand/context'219-```220-221-**Change**222-223-```diff224-- type UseContextStore225-```226-227-**Migration**228-229-Use `typeof MyContext.useStore` instead230-231-## `createContext`232-233-**Applicable imports**234-235-```ts236-import createContext from 'zustand/context'237-```238-239-**Change**240-241-```diff242- createContext:243-- <State, Store = StoreApi<State>>() => ...244-+ <Store>() => ...245-```246-247-**Migration**248-249-Replace `createContext<T>()` with `createContext<StoreApi<T>>()`,250-and `createContext<T, S>()` with `createContext<S>()`.251-252-## `combine`, `devtools`, `subscribeWithSelector`253-254-**Applicable imports**255-256-```ts257-import { combine } from 'zustand/middleware'258-import { devtools } from 'zustand/middleware'259-import { subscribeWithSelector } from 'zustand/middleware'260-```261-262-**Change**263-264-```diff265-- combine:266-- <T, U>(...) => ...267-+ combine:268-+ <T, U, Mps, Mcs>(...) => ...269-270-- devtools:271-- <T>(...) => ...272-+ devtools:273-+ <T, Mps, Mcs>(...) => ...274-275-- subscribeWithSelector:276-- <T>(...) => ...277-+ subscribeWithSelector:278-+ <T, Mps, Mcs>(...) => ...279-```280-281-**Migration**282-283-If you are not passing any type parameters284-to `combine`, `devtools`, or `subscribeWithSelector`,285-no migration is required.286-287-If you are,288-remove all the type parameters,289-as they are inferred automatically.290-291-## `persist`292-293-**Applicable imports**294-295-```ts296-import { persist } from 'zustand/middleware'297-```298-299-**Change**300-301-```diff302-- persist:303-- <T, U = Partial<T>>(...) => ...304-+ persist:305-+ <T, Mps, Mcs, U = T>(...) => ...306-```307-308-**Migration**309-310-If you are passing any type parameters,311-remove them as they are inferred automatically.312-313-Next, if you are passing the `partialize` option,314-there is no further steps required for migration.315-316-If you are **not** passing the `partialize` option,317-you might see some compilation errors.318-If you do not see any,319-there is no further migration required.320-321-The type of partialized state is now `T` instead of `Partial<T>`,322-which aligns with the runtime behavior of the default `partialize`,323-which is an identity (`s => s`).324-325-If you see some compilation errors,326-you have to find and fix the errors yourself,327-because they might be indicative of unsound code.328-Alternatively, the workaround will be passing329-`s => s as Partial<typeof s>` to `partialize`.330-If your partialized state is truly `Partial<T>`,331-you should not encounter any bugs.332-333-The runtime behavior has not changed,334-only the types are now correct.335-336-## `redux`337-338-**Applicable imports**339-340-```ts341-import { redux } from 'zustand/middleware'342-```343-344-**Change**345-346-```diff347-- redux:348-- <T, A>(...) => ...349-+ redux:350-+ <T, A, Mps, Mcs>(...) => ...351-```352-353-**Migration**354-355-If you are not passing any type parameters to `redux`,356-no migration is required.357-358-If you are,359-remove all the type parameters,360-and annotate only the second (action) parameter.361-That is, replace `redux<T, A>((state, action) => ..., ...)`362-with `redux((state, action: A) => ..., ...)`.deleted:docs/migrations/migrating-to-v5.md-241 removed
1----2-title: How to Migrate to v5 from v43-nav: 234----5-6-# How to Migrate to v5 from v47-8-We highly recommend to update to the latest version of v4, before migrating to v5. It will show all deprecation warnings without breaking your app.9-10-## Changes in v511-12-- Drop default exports13-- Drop deprecated features14-- Make React 18 the minimum required version15-- Make use-sync-external-store a peer dependency (required for `createWithEqualityFn` and `useStoreWithEqualityFn` in `zustand/traditional`)16-- Make TypeScript 4.5 the minimum required version17-- Drop UMD/SystemJS support18-- Organize entry points in the package.json19-- Drop ES5 support20-- Stricter types when setState's replace flag is set21-- Persist middleware behavioral change22-- Other small improvements (technically breaking changes)23-24-## Migration Guide25-26-### Using custom equality functions such as `shallow`27-28-The `create` function in v5 does not support customizing equality function.29-30-If you use custom equality function such as `shallow`,31-the easiest migration is to use `createWithEqualityFn`.32-33-```js34-// v435-import { create } from 'zustand'36-import { shallow } from 'zustand/shallow'37-38-const useCountStore = create((set) => ({39- count: 0,40- text: 'hello',41- // ...42-}))43-44-const Component = () => {45- const { count, text } = useCountStore(46- (state) => ({47- count: state.count,48- text: state.text,49- }),50- shallow,51- )52- // ...53-}54-```55-56-That can be done with `createWithEqualityFn` in v5:57-58-```bash59-npm install use-sync-external-store60-```61-62-```js63-// v564-import { createWithEqualityFn as create } from 'zustand/traditional'65-66-// The rest is the same as v467-```68-69-Alternatively, for the `shallow` use case, you can use `useShallow` hook:70-71-```js72-// v573-import { create } from 'zustand'74-import { useShallow } from 'zustand/shallow'75-76-const useCountStore = create((set) => ({77- count: 0,78- text: 'hello',79- // ...80-}))81-82-const Component = () => {83- const { count, text } = useCountStore(84- useShallow((state) => ({85- count: state.count,86- text: state.text,87- })),88- )89- // ...90-}91-```92-93-### Requiring stable selector outputs94-95-There is a behavioral change in v5 to match React default behavior.96-If a selector returns a new reference, it may cause infinite loops.97-98-For example, this may cause infinite loops.99-100-```js101-// v4102-const [searchValue, setSearchValue] = useStore((state) => [103- state.searchValue,104- state.setSearchValue,105-])106-```107-108-The error message will be something like this:109-110-```plaintext111-Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.112-```113-114-To fix it, use the `useShallow` hook, which will return a stable reference.115-116-```js117-// v5118-import { useShallow } from 'zustand/shallow'119-120-const [searchValue, setSearchValue] = useStore(121- useShallow((state) => [state.searchValue, state.setSearchValue]),122-)123-```124-125-Here's another example that may cause infinite loops.126-127-```js128-// v4129-const action = useMainStore((state) => {130- return state.action ?? () => {}131-})132-```133-134-To fix it, make sure the selector function returns a stable reference.135-136-```js137-// v5138-139-const FALLBACK_ACTION = () => {}140-141-const action = useMainStore((state) => {142- return state.action ?? FALLBACK_ACTION143-})144-```145-146-Alternatively, if you need v4 behavior, `createWithEqualityFn` will do.147-148-```js149-// v5150-import { createWithEqualityFn as create } from 'zustand/traditional'151-```152-153-### Stricter types when setState's replace flag is set (Typescript only)154-155-```diff156-- setState:157-- (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean | undefined) => void;158-+ setState:159-+ (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: false) => void;160-+ (state: T | ((state: T) => T), replace: true) => void;161-```162-163-If you are not using the `replace` flag, no migration is required.164-165-If you are using the `replace` flag and it's set to `true`, you must provide a complete state object.166-This change ensures that `store.setState({}, true)` (which results in an invalid state) is no longer considered valid.167-168-**Examples:**169-170-```ts171-// Partial state update (valid)172-store.setState({ key: 'value' })173-174-// Complete state replacement (valid)175-store.setState({ key: 'value' }, true)176-177-// Incomplete state replacement (invalid)178-store.setState({}, true) // Error179-```180-181-#### Handling Dynamic `replace` Flag182-183-If the value of the `replace` flag is dynamic and determined at runtime, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:184-185-```ts186-const replaceFlag = Math.random() > 0.5187-const args = [{ bears: 5 }, replaceFlag] as Parameters<188- typeof useBearStore.setState189->190-store.setState(...args)191-```192-193-#### Persist middleware no longer stores item at store creation194-195-Previously, the `persist` middleware stored the initial state during store creation. This behavior has been removed in v5 (and v4.5.5).196-197-For example, in the following code, the initial state is stored in the storage.198-199-```js200-// v4201-import { create } from 'zustand'202-import { persist } from 'zustand/middleware'203-204-const useCountStore = create(205- persist(206- () => ({207- count: Math.floor(Math.random() * 1000),208- }),209- {210- name: 'count',211- },212- ),213-)214-```215-216-In v5, this is no longer the case, and you need to explicitly set the state after store creation.217-218-```js219-// v5220-import { create } from 'zustand'221-import { persist } from 'zustand/middleware'222-223-const useCountStore = create(224- persist(225- () => ({226- count: 0,227- }),228- {229- name: 'count',230- },231- ),232-)233-useCountStore.setState({234- count: Math.floor(Math.random() * 1000),235-})236-```237-238-## Links239-240-- https://github.com/pmndrs/zustand/pull/2138241-- https://github.com/pmndrs/zustand/pull/2580deleted:docs/previous-versions/zustand-v3-create-context.md-145 removed
1----2-title: createContext from zustand/context3-nav: 214----5-6-A special `createContext` is provided since v3.5,7-which avoids misusing the store hook.8-9-> **Note**: This function is deprecated in v4 and will be removed in v5. See [Migration](#migration).10-11-```jsx12-import create from 'zustand'13-import createContext from 'zustand/context'14-15-const { Provider, useStore } = createContext()16-17-const createStore = () => create(...)18-19-const App = () => (20- <Provider createStore={createStore}>21- ...22- </Provider>23-)24-25-const Component = () => {26- const state = useStore()27- const slice = useStore(selector)28- ...29-```30-31-## createContext usage in real components32-33-```jsx34-import create from "zustand";35-import createContext from "zustand/context";36-37-// Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.38-39-const { Provider, useStore } = createContext();40-41-const createStore = () =>42- create((set) => ({43- bears: 0,44- increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),45- removeAllBears: () => set({ bears: 0 })46- }));47-48-const Button = () => {49- return (50- {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}51- <Provider createStore={createStore}>52- <ButtonChild />53- </Provider>54- );55-};56-57-const ButtonChild = () => {58- const state = useStore();59- return (60- <div>61- {state.bears}62- <button63- onClick={() => {64- state.increasePopulation();65- }}66- >67- +68- </button>69- </div>70- );71-};72-73-export default function App() {74- return (75- <div className="App">76- <Button />77- <Button />78- </div>79- );80-}81-```82-83-## createContext usage with initialization from props84-85-```tsx86-import create from 'zustand'87-import createContext from 'zustand/context'88-89-const { Provider, useStore } = createContext()90-91-export default function App({ initialBears }) {92- return (93- <Provider94- createStore={() =>95- create((set) => ({96- bears: initialBears,97- increase: () => set((state) => ({ bears: state.bears + 1 })),98- }))99- }100- >101- <Button />102- </Provider>103- )104-}105-```106-107-## Migration108-109-Discussion: https://github.com/pmndrs/zustand/discussions/1276110-111-Here's the new context usage with v4 API.112-113-```jsx114-import { createContext, useContext, useRef } from 'react'115-import { createStore, useStore } from 'zustand'116-117-const StoreContext = createContext(null)118-119-const StoreProvider = ({ children }) => {120- const storeRef = useRef()121- if (storeRef.current === null) {122- storeRef.current = createStore((set) => ({123- // ...124- }))125- }126- return (127- <StoreContext.Provider value={storeRef.current}>128- {children}129- </StoreContext.Provider>130- )131-}132-133-const useStoreInContext = (selector) => {134- const store = useContext(StoreContext)135- if (!store) {136- throw new Error('Missing StoreProvider')137- }138- return useStore(store, selector)139-}140-```141-142-Or reach out to some third-party libraries that provide Zustand v3-like APIs:143-144-- <https://github.com/charkour/zustand-di>145-- <https://github.com/arvinxx/zustand-utils>added:docs/public/bear.jpgbinary
A binary file, added.
added:docs/public/favicon.icobinary
A binary file, added.
added:docs/reference/apis/create-store.md+517 added
1+---2+title: createStore3+description: How to create vanilla stores4+nav: 225+---6+7+`createStore` lets you create a vanilla store that exposes API utilities.8+9+```js10+const someStore = createStore(stateCreatorFn)11+```12+13+- [Types](#types)14+ - [Signature](#signature)15+- [Reference](#reference)16+- [Usage](#usage)17+ - [Updating state based on previous state](#updating-state-based-on-previous-state)18+ - [Updating Primitives in State](#updating-primitives-in-state)19+ - [Updating Objects in State](#updating-objects-in-state)20+ - [Updating Arrays in State](#updating-arrays-in-state)21+ - [Subscribing to state updates](#subscribing-to-state-updates)22+- [Troubleshooting](#troubleshooting)23+ - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)24+25+## Types26+27+### Signature28+29+```ts30+createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>31+```32+33+## Reference34+35+### `createStore(stateCreatorFn)`36+37+#### Parameters38+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+44+`createStore` returns a vanilla store that exposes API utilities, `setState`, `getState`,45+`getInitialState` and `subscribe`.46+47+## Usage48+49+### Updating state based on previous state50+51+This example shows how you can support **updater functions** within **actions**.52+53+```tsx54+import { createStore } from 'zustand/vanilla'55+56+type AgeStoreState = { age: number }57+58+type AgeStoreActions = {59+ setAge: (60+ nextAge:61+ | AgeStoreState['age']62+ | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),63+ ) => void64+}65+66+type AgeStore = AgeStoreState & AgeStoreActions67+68+const ageStore = createStore<AgeStore>()((set) => ({69+ age: 42,70+ setAge: (nextAge) =>71+ set((state) => ({72+ age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,73+ })),74+}))75+76+function increment() {77+ ageStore.getState().setAge((currentAge) => currentAge + 1)78+}79+80+const $yourAgeHeading = document.getElementById(81+ 'your-age',82+) as HTMLHeadingElement83+const $incrementBy3Button = document.getElementById(84+ 'increment-by-3',85+) as HTMLButtonElement86+const $incrementBy1Button = document.getElementById(87+ 'increment-by-1',88+) as HTMLButtonElement89+90+$incrementBy3Button.addEventListener('click', () => {91+ increment()92+ increment()93+ increment()94+})95+96+$incrementBy1Button.addEventListener('click', () => {97+ increment()98+})99+100+const render: Parameters<typeof ageStore.subscribe>[0] = (state) => {101+ $yourAgeHeading.innerHTML = `Your age: ${state.age}`102+}103+104+render(ageStore.getInitialState(), ageStore.getInitialState())105+106+ageStore.subscribe(render)107+```108+109+Here's the `html` code110+111+```html112+<h1 id="your-age"></h1>113+<button id="increment-by-3" type="button">+3</button>114+<button id="increment-by-1" type="button">+1</button>115+```116+117+### Updating Primitives in State118+119+State can hold any kind of JavaScript value. When you want to update built-in primitive values like120+numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied121+correctly, and avoid unexpected behaviors.122+123+> [!NOTE]124+> By default, `set` function performs a shallow merge. If you need to completely replace125+> the state with a new one, use the `replace` parameter set to `true`126+127+```ts128+import { createStore } from 'zustand/vanilla'129+130+type XStore = number131+132+const xStore = createStore<XStore>()(() => 0)133+134+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement135+const $dot = document.getElementById('dot') as HTMLDivElement136+137+$dotContainer.addEventListener('pointermove', (event) => {138+ xStore.setState(event.clientX, true)139+})140+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+147+xStore.subscribe(render)148+```149+150+Here's the `html` code151+152+```html153+<div154+ id="dot-container"155+ style="position: relative; width: 100vw; height: 100vh;"156+>157+ <div158+ id="dot"159+ style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"160+ ></div>161+</div>162+```163+164+### Updating Objects in State165+166+Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store167+them in state. Instead, when you want to update an object, you need to create a new one (or make a168+copy of an existing one), and then set the state to use the new object.169+170+By default, `set` function performs a shallow merge. For most updates where you only need to modify171+specific properties, the default shallow merge is preferred as it's more efficient. To completely172+replace the state with a new one, use the `replace` parameter set to `true` with caution, as it173+discards any existing nested data within the state.174+175+```ts176+import { createStore } from 'zustand/vanilla'177+178+type PositionStoreState = { position: { x: number; y: number } }179+180+type PositionStoreActions = {181+ setPosition: (nextPosition: PositionStoreState['position']) => void182+}183+184+type PositionStore = PositionStoreState & PositionStoreActions185+186+const positionStore = createStore<PositionStore>()((set) => ({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 HTMLDivElement193+194+$dotContainer.addEventListener('pointermove', (event) => {195+ positionStore.getState().setPosition({196+ x: event.clientX,197+ y: event.clientY,198+ })199+})200+201+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {202+ $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`203+}204+205+render(positionStore.getInitialState(), positionStore.getInitialState())206+207+positionStore.subscribe(render)208+```209+210+Here's the `html` code211+212+```html213+<div214+ id="dot-container"215+ style="position: relative; width: 100vw; height: 100vh;"216+>217+ <div218+ id="dot"219+ style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"220+ ></div>221+</div>222+```223+224+### Updating Arrays in State225+226+Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in227+state. Just like with objects, when you want to update an array stored in state, you need to create228+a new one (or make a copy of an existing one), and then set state to use the new array.229+230+By default, `set` function performs a shallow merge. To update array values we should assign new231+values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely232+replace the state with a new one, use the `replace` parameter set to `true`.233+234+> [!IMPORTANT]235+> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,236+> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid237+> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,238+> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.239+240+```ts241+import { createStore } from 'zustand/vanilla'242+243+type PositionStore = [number, number]244+245+const positionStore = createStore<PositionStore>()(() => [0, 0])246+247+const $dotContainer = document.getElementById('dot-container') as HTMLDivElement248+const $dot = document.getElementById('dot') as HTMLDivElement249+250+$dotContainer.addEventListener('pointermove', (event) => {251+ positionStore.setState([event.clientX, event.clientY], true)252+})253+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+260+positionStore.subscribe(render)261+```262+263+Here's the `html` code264+265+```html266+<div267+ id="dot-container"268+ style="position: relative; width: 100vw; height: 100vh;"269+>270+ <div271+ id="dot"272+ style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"273+ ></div>274+</div>275+```276+277+### Subscribing to state updates278+279+By subscribing to state updates, you register a callback that fires whenever the store's state280+updates. We can use `subscribe` for external state management.281+282+```ts283+import { createStore } from 'zustand/vanilla'284+285+type PositionStoreState = { position: { x: number; y: number } }286+287+type PositionStoreActions = {288+ setPosition: (nextPosition: PositionStoreState['position']) => void289+}290+291+type PositionStore = PositionStoreState & PositionStoreActions292+293+const positionStore = createStore<PositionStore>()((set) => ({294+ position: { x: 0, y: 0 },295+ setPosition: (position) => set({ position }),296+}))297+298+const $dot = document.getElementById('dot') as HTMLDivElement299+300+$dot.addEventListener('mouseenter', (event) => {301+ const parent = event.currentTarget.parentElement302+ const parentWidth = parent.clientWidth303+ const parentHeight = parent.clientHeight304+305+ positionStore.getState().setPosition({306+ x: Math.ceil(Math.random() * parentWidth),307+ y: Math.ceil(Math.random() * parentHeight),308+ })309+})310+311+const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {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) => {320+ console.log('new position', { position: state.position })321+}322+323+positionStore.subscribe(logger)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+## Troubleshooting341+342+### I’ve updated the state, but the screen doesn’t update343+344+In the previous example, the `position` object is always created fresh from the current cursor345+position. But often, you will want to include existing data as a part of the new object you’re346+creating. For example, you may want to update only one field in a form, but keep the previous347+values for all other fields.348+349+These input fields don’t work because the `oninput` handlers mutate the state:350+351+```ts352+import { createStore } from 'zustand/vanilla'353+354+type PersonStoreState = {355+ person: { firstName: string; lastName: string; email: string }356+}357+358+type PersonStoreActions = {359+ setPerson: (nextPerson: PersonStoreState['person']) => void360+}361+362+type PersonStore = PersonStoreState & PersonStoreActions363+364+const personStore = createStore<PersonStore>()((set) => ({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',375+) as HTMLInputElement376+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement377+const $emailInput = document.getElementById('email') as HTMLInputElement378+const $result = document.getElementById('result') as HTMLDivElement379+380+function handleFirstNameChange(event: Event) {381+ personStore.getState().person.firstName = (event.target as any).value382+}383+384+function handleLastNameChange(event: Event) {385+ personStore.getState().person.lastName = (event.target as any).value386+}387+388+function handleEmailChange(event: Event) {389+ 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) => {397+ $firstNameInput.value = state.person.firstName398+ $lastNameInput.value = state.person.lastName399+ $emailInput.value = state.person.email400+401+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`402+}403+404+render(personStore.getInitialState(), personStore.getInitialState())405+406+personStore.subscribe(render)407+```408+409+Here's the `html` code410+411+```html412+<label style="display: block">413+ First name:414+ <input id="first-name" />415+</label>416+<label style="display: block">417+ Last name:418+ <input id="last-name" />419+</label>420+<label style="display: block">421+ Email:422+ <input id="email" />423+</label>424+<p id="result"></p>425+```426+427+For example, this line mutates the state from a past render:428+429+```ts430+personStore.getState().firstName = (e.target as any).value431+```432+433+The reliable way to get the behavior you’re looking for is to create a new object and pass it to434+`setPerson`. But here you want to also copy the existing data into it because only one of the435+fields has changed:436+437+```ts438+personStore.getState().setPerson({439+ firstName: e.target.value, // New first name from the input440+})441+```442+443+> [!NOTE]444+> We don’t need to copy every property separately due to `set` function performing shallow merge by445+> default.446+447+Now the form works!448+449+Notice how you didn’t declare a separate state variable for each input field. For large forms,450+keeping all data grouped in an object is very convenient—as long as you update it correctly!451+452+```ts {32-34,38-40,44-46}453+import { createStore } from 'zustand/vanilla'454+455+type PersonStoreState = {456+ person: { firstName: string; lastName: string; email: string }457+}458+459+type PersonStoreActions = {460+ setPerson: (nextPerson: PersonStoreState['person']) => void461+}462+463+type PersonStore = PersonStoreState & PersonStoreActions464+465+const personStore = createStore<PersonStore>()((set) => ({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',476+) as HTMLInputElement477+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement478+const $emailInput = document.getElementById('email') as HTMLInputElement479+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+502+$firstNameInput.addEventListener('input', handleFirstNameChange)503+$lastNameInput.addEventListener('input', handleLastNameChange)504+$emailInput.addEventListener('input', handleEmailChange)505+506+const render: Parameters<typeof personStore.subscribe>[0] = (state) => {507+ $firstNameInput.value = state.person.firstName508+ $lastNameInput.value = state.person.lastName509+ $emailInput.value = state.person.email510+511+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`512+}513+514+render(personStore.getInitialState(), personStore.getInitialState())515+516+personStore.subscribe(render)517+```added:docs/reference/apis/create-with-equality-fn.md+607 added
1+---2+title: createWithEqualityFn3+description: How to create efficient stores4+tag: react5+nav: 236+---7+8+`createWithEqualityFn` lets you create a React Hook with API utilities attached, just like `create`.9+However, it offers a way to define a custom equality check. This allows for more granular control10+over when components re-render, improving performance and responsiveness.11+12+> [!IMPORTANT]13+> In order to use `createWithEqualityFn` from `zustand/traditional` you need to install14+> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.15+16+```js17+const useSomeStore = createWithEqualityFn(stateCreatorFn, equalityFn)18+```19+20+- [Types](#types)21+ - [Signature](#createwithequalityfn-signature)22+- [Reference](#reference)23+- [Usage](#usage)24+ - [Updating state based on previous state](#updating-state-based-on-previous-state)25+ - [Updating Primitives in State](#updating-primitives-in-state)26+ - [Updating Objects in State](#updating-objects-in-state)27+ - [Updating Arrays in State](#updating-arrays-in-state)28+ - [Updating state with no store actions](#updating-state-with-no-store-actions)29+ - [Subscribing to state updates](#subscribing-to-state-updates)30+- [Troubleshooting](#troubleshooting)31+ - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)32+33+## Types34+35+### Signature36+37+```ts38+createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, equalityFn?: (a: T, b: T) => boolean): UseBoundStore<StoreApi<T>>39+```40+41+## Reference42+43+### `createWithEqualityFn(stateCreatorFn)`44+45+#### Parameters46+47+- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.48+ Usually, you will return an object with the methods you want to expose.49+- **optional** `equalityFn`: Defaults to `Object.is`. A function that lets you skip re-renders.50+51+#### Returns52+53+`createWithEqualityFn` returns a React Hook with API utilities attached, just like `create`. It54+lets you return data that is based on current state, using a selector function, and lets you skip55+re-renders using an equality function. It should take a selector function, and an equality function56+as arguments.57+58+## Usage59+60+### Updating state based on previous state61+62+To update a state based on previous state we should use **updater functions**. Read more63+about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).64+65+This example shows how you can support **updater functions** within **actions**.66+67+```tsx68+import { createWithEqualityFn } from 'zustand/traditional'69+import { shallow } from 'zustand/vanilla/shallow'70+71+type AgeStoreState = { age: number }72+73+type AgeStoreActions = {74+ setAge: (75+ nextAge:76+ | AgeStoreState['age']77+ | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),78+ ) => void79+}80+81+type AgeStore = AgeStoreState & AgeStoreActions82+83+const useAgeStore = createWithEqualityFn<AgeStore>()(84+ (set) => ({85+ age: 42,86+ setAge: (nextAge) =>87+ set((state) => ({88+ age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,89+ })),90+ }),91+ shallow,92+)93+94+export default function App() {95+ const age = useAgeStore((state) => state.age)96+ const setAge = useAgeStore((state) => state.setAge)97+98+ function increment() {99+ setAge((currentAge) => currentAge + 1)100+ }101+102+ return (103+ <>104+ <h1>Your age: {age}</h1>105+ <button106+ type="button"107+ onClick={() => {108+ increment()109+ increment()110+ increment()111+ }}112+ >113+ +3114+ </button>115+ <button116+ type="button"117+ onClick={() => {118+ increment()119+ }}120+ >121+ +1122+ </button>123+ </>124+ )125+}126+```127+128+### Updating Primitives in State129+130+State can hold any kind of JavaScript value. When you want to update built-in primitive values like131+numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied132+correctly, and avoid unexpected behaviors.133+134+> [!NOTE]135+> By default, `set` function performs a shallow merge. If you need to completely replace136+> the state with a new one, use the `replace` parameter set to `true`137+138+```tsx139+import { createWithEqualityFn } from 'zustand/traditional'140+import { shallow } from 'zustand/vanilla/shallow'141+142+type XStore = number143+144+const useXStore = createWithEqualityFn<XStore>()(() => 0, shallow)145+146+export default function MovingDot() {147+ const x = useXStore()148+ const setX = (nextX: number) => {149+ useXStore.setState(nextX, true)150+ }151+ const position = { y: 0, x }152+153+ return (154+ <div155+ onPointerMove={(e) => {156+ setX(e.clientX)157+ }}158+ style={{159+ position: 'relative',160+ width: '100vw',161+ height: '100vh',162+ }}163+ >164+ <div165+ style={{166+ position: 'absolute',167+ backgroundColor: 'red',168+ borderRadius: '50%',169+ transform: `translate(${position.x}px, ${position.y}px)`,170+ left: -10,171+ top: -10,172+ width: 20,173+ height: 20,174+ }}175+ />176+ </div>177+ )178+}179+```180+181+### Updating Objects in State182+183+Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store184+them in state. Instead, when you want to update an object, you need to create a new one (or make a185+copy of an existing one), and then set the state to use the new object.186+187+By default, `set` function performs a shallow merge. For most updates where you only need to modify188+specific properties, the default shallow merge is preferred as it's more efficient. To completely189+replace the state with a new one, use the `replace` parameter set to `true` with caution, as it190+discards any existing nested data within the state.191+192+```tsx193+import { createWithEqualityFn } from 'zustand/traditional'194+import { shallow } from 'zustand/vanilla/shallow'195+196+type PositionStoreState = { position: { x: number; y: number } }197+198+type PositionStoreActions = {199+ setPosition: (nextPosition: PositionStoreState['position']) => void200+}201+202+type PositionStore = PositionStoreState & PositionStoreActions203+204+const usePositionStore = createWithEqualityFn<PositionStore>()(205+ (set) => ({206+ position: { x: 0, y: 0 },207+ setPosition: (position) => set({ position }),208+ }),209+ shallow,210+)211+212+export default function MovingDot() {213+ const position = usePositionStore((state) => state.position)214+ const setPosition = usePositionStore((state) => state.setPosition)215+216+ return (217+ <div218+ onPointerMove={(e) => {219+ setPosition({220+ x: e.clientX,221+ y: e.clientY,222+ })223+ }}224+ style={{225+ position: 'relative',226+ width: '100vw',227+ height: '100vh',228+ }}229+ >230+ <div231+ style={{232+ position: 'absolute',233+ backgroundColor: 'red',234+ borderRadius: '50%',235+ transform: `translate(${position.x}px, ${position.y}px)`,236+ left: -10,237+ top: -10,238+ width: 20,239+ height: 20,240+ }}241+ />242+ </div>243+ )244+}245+```246+247+### Updating Arrays in State248+249+Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in250+state. Just like with objects, when you want to update an array stored in state, you need to create251+a new one (or make a copy of an existing one), and then set state to use the new array.252+253+By default, `set` function performs a shallow merge. To update array values we should assign new254+values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely255+replace the state with a new one, use the `replace` parameter set to `true`.256+257+> [!IMPORTANT]258+> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,259+> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid260+> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,261+> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.262+263+```tsx264+import { createWithEqualityFn } from 'zustand/traditional'265+import { shallow } from 'zustand/vanilla/shallow'266+267+type PositionStore = [number, number]268+269+const usePositionStore = createWithEqualityFn<PositionStore>()(270+ () => [0, 0],271+ shallow,272+)273+274+export default function MovingDot() {275+ const [x, y] = usePositionStore()276+ const position = { x, y }277+ const setPosition: typeof usePositionStore.setState = (nextPosition) => {278+ usePositionStore.setState(nextPosition, true)279+ }280+281+ return (282+ <div283+ onPointerMove={(e) => {284+ setPosition([e.clientX, e.clientY])285+ }}286+ style={{287+ position: 'relative',288+ width: '100vw',289+ height: '100vh',290+ }}291+ >292+ <div293+ style={{294+ position: 'absolute',295+ backgroundColor: 'red',296+ borderRadius: '50%',297+ transform: `translate(${position.x}px, ${position.y}px)`,298+ left: -10,299+ top: -10,300+ width: 20,301+ height: 20,302+ }}303+ />304+ </div>305+ )306+}307+```308+309+### Updating state with no store actions310+311+Defining actions at module level, external to the store have a few advantages like: it doesn't312+require a hook to call an action, and it facilitates code splitting.313+314+> [!NOTE]315+> The recommended way is to colocate actions and states within the store (let your actions be316+> located together with your state).317+318+```tsx319+import { createWithEqualityFn } from 'zustand/traditional'320+import { shallow } from 'zustand/vanilla/shallow'321+322+const usePositionStore = createWithEqualityFn<{323+ x: number324+ y: number325+}>()(() => ({ x: 0, y: 0 }), shallow)326+327+const setPosition: typeof usePositionStore.setState = (nextPosition) => {328+ usePositionStore.setState(nextPosition)329+}330+331+export default function MovingDot() {332+ const position = usePositionStore()333+334+ return (335+ <div336+ style={{337+ position: 'relative',338+ width: '100vw',339+ height: '100vh',340+ }}341+ >342+ <div343+ style={{344+ position: 'absolute',345+ backgroundColor: 'red',346+ borderRadius: '50%',347+ transform: `translate(${position.x}px, ${position.y}px)`,348+ left: -10,349+ top: -10,350+ width: 20,351+ height: 20,352+ }}353+ onMouseEnter={(event) => {354+ const parent = event.currentTarget.parentElement355+ const parentWidth = parent.clientWidth356+ const parentHeight = parent.clientHeight357+358+ setPosition({359+ x: Math.ceil(Math.random() * parentWidth),360+ y: Math.ceil(Math.random() * parentHeight),361+ })362+ }}363+ />364+ </div>365+ )366+}367+```368+369+### Subscribing to state updates370+371+By subscribing to state updates, you register a callback that fires whenever the store's state372+updates. We can use `subscribe` for external state management.373+374+```tsx375+import { useEffect } from 'react'376+import { createWithEqualityFn } from 'zustand/traditional'377+import { shallow } from 'zustand/vanilla/shallow'378+379+type PositionStoreState = { position: { x: number; y: number } }380+381+type PositionStoreActions = {382+ setPosition: (nextPosition: PositionStoreState['position']) => void383+}384+385+type PositionStore = PositionStoreState & PositionStoreActions386+387+const usePositionStore = createWithEqualityFn<PositionStore>()(388+ (set) => ({389+ position: { x: 0, y: 0 },390+ setPosition: (nextPosition) => set({ position: nextPosition }),391+ }),392+ shallow,393+)394+395+export default function MovingDot() {396+ const position = usePositionStore((state) => state.position)397+ const setPosition = usePositionStore((state) => state.setPosition)398+399+ useEffect(() => {400+ const unsubscribePositionStore = usePositionStore.subscribe(401+ ({ position }) => {402+ console.log('new position', { position })403+ },404+ )405+406+ return () => {407+ unsubscribePositionStore()408+ }409+ }, [])410+411+ return (412+ <div413+ style={{414+ position: 'relative',415+ width: '100vw',416+ height: '100vh',417+ }}418+ >419+ <div420+ style={{421+ position: 'absolute',422+ backgroundColor: 'red',423+ borderRadius: '50%',424+ transform: `translate(${position.x}px, ${position.y}px)`,425+ left: -10,426+ top: -10,427+ width: 20,428+ height: 20,429+ }}430+ onMouseEnter={(event) => {431+ const parent = event.currentTarget.parentElement432+ const parentWidth = parent.clientWidth433+ const parentHeight = parent.clientHeight434+435+ setPosition({436+ x: Math.ceil(Math.random() * parentWidth),437+ y: Math.ceil(Math.random() * parentHeight),438+ })439+ }}440+ />441+ </div>442+ )443+}444+```445+446+## Troubleshooting447+448+### I’ve updated the state, but the screen doesn’t update449+450+In the previous example, the `position` object is always created fresh from the current cursor451+position. But often, you will want to include existing data as a part of the new object you’re452+creating. For example, you may want to update only one field in a form, but keep the previous453+values for all other fields.454+455+These input fields don’t work because the `onChange` handlers mutate the state:456+457+```tsx458+import { createWithEqualityFn } from 'zustand/traditional'459+import { shallow } from 'zustand/vanilla/shallow'460+461+type PersonStoreState = {462+ person: { firstName: string; lastName: string; email: string }463+}464+465+type PersonStoreActions = {466+ setPerson: (nextPerson: PersonStoreState['person']) => void467+}468+469+type PersonStore = PersonStoreState & PersonStoreActions470+471+const usePersonStore = createWithEqualityFn<PersonStore>()(472+ (set) => ({473+ person: {474+ firstName: 'Barbara',475+ lastName: 'Hepworth',476+ email: 'bhepworth@sculpture.com',477+ },478+ setPerson: (person) => set({ person }),479+ }),480+ shallow,481+)482+483+export default function Form() {484+ const person = usePersonStore((state) => state.person)485+ const setPerson = usePersonStore((state) => state.setPerson)486+487+ function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {488+ person.firstName = e.target.value489+ }490+491+ function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {492+ person.lastName = e.target.value493+ }494+495+ function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {496+ person.email = e.target.value497+ }498+499+ return (500+ <>501+ <label style={{ display: 'block' }}>502+ First name:503+ <input value={person.firstName} onChange={handleFirstNameChange} />504+ </label>505+ <label style={{ display: 'block' }}>506+ Last name:507+ <input value={person.lastName} onChange={handleLastNameChange} />508+ </label>509+ <label style={{ display: 'block' }}>510+ Email:511+ <input value={person.email} onChange={handleEmailChange} />512+ </label>513+ <p>514+ {person.firstName} {person.lastName} ({person.email})515+ </p>516+ </>517+ )518+}519+```520+521+For example, this line mutates the state from a past render:522+523+```tsx524+person.firstName = e.target.value525+```526+527+The reliable way to get the behavior you’re looking for is to create a new object and pass it to528+`setPerson`. But here you want to also copy the existing data into it because only one of the529+fields has changed:530+531+```ts532+setPerson({ ...person, firstName: e.target.value }) // New first name from the input533+```534+535+> [!NOTE]536+> We don’t need to copy every property separately due to `set` function performing shallow merge by537+> default.538+539+Now the form works!540+541+Notice how you didn’t declare a separate state variable for each input field. For large forms,542+keeping all data grouped in an object is very convenient—as long as you update it correctly!543+544+```tsx {32,36,40}545+import { type ChangeEvent } from 'react'546+import { createWithEqualityFn } from 'zustand/traditional'547+import { shallow } from 'zustand/vanilla/shallow'548+549+type PersonStoreState = {550+ person: { firstName: string; lastName: string; email: string }551+}552+553+type PersonStoreActions = {554+ setPerson: (nextPerson: PersonStoreState['person']) => void555+}556+557+type PersonStore = PersonStoreState & PersonStoreActions558+559+const usePersonStore = createWithEqualityFn<PersonStore>()(560+ (set) => ({561+ person: {562+ firstName: 'Barbara',563+ lastName: 'Hepworth',564+ email: 'bhepworth@sculpture.com',565+ },566+ setPerson: (nextPerson) => set({ person: nextPerson }),567+ }),568+ shallow,569+)570+571+export default function Form() {572+ const person = usePersonStore((state) => state.person)573+ const setPerson = usePersonStore((state) => state.setPerson)574+575+ function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {576+ setPerson({ ...person, firstName: e.target.value })577+ }578+579+ function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {580+ setPerson({ ...person, lastName: e.target.value })581+ }582+583+ function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {584+ setPerson({ ...person, email: e.target.value })585+ }586+587+ return (588+ <>589+ <label style={{ display: 'block' }}>590+ First name:591+ <input value={person.firstName} onChange={handleFirstNameChange} />592+ </label>593+ <label style={{ display: 'block' }}>594+ Last name:595+ <input value={person.lastName} onChange={handleLastNameChange} />596+ </label>597+ <label style={{ display: 'block' }}>598+ Email:599+ <input value={person.email} onChange={handleEmailChange} />600+ </label>601+ <p>602+ {person.firstName} {person.lastName} ({person.email})603+ </p>604+ </>605+ )606+}607+```added:docs/reference/apis/create.md+571 added
1+---2+title: create3+description: How to create stores4+tag: react5+nav: 216+---7+8+`create` lets you create a React Hook with API utilities attached.9+10+```js11+const useSomeStore = create(stateCreatorFn)12+```13+14+- [Types](#types)15+ - [Signature](#create-signature)16+- [Reference](#reference)17+- [Usage](#usage)18+ - [Updating state based on previous state](#updating-state-based-on-previous-state)19+ - [Updating Primitives in State](#updating-primitives-in-state)20+ - [Updating Objects in State](#updating-objects-in-state)21+ - [Updating Arrays in State](#updating-arrays-in-state)22+ - [Updating state with no store actions](#updating-state-with-no-store-actions)23+ - [Subscribing to state updates](#subscribing-to-state-updates)24+- [Troubleshooting](#troubleshooting)25+ - [I’ve updated the state, but the screen doesn’t update](#ive-updated-the-state-but-the-screen-doesnt-update)26+27+## Types28+29+### Signature30+31+```ts32+create<T>()(stateCreatorFn: StateCreator<T, [], []>): UseBoundStore<StoreApi<T>>33+```34+35+## Reference36+37+### `create(stateCreatorFn)`38+39+#### Parameters40+41+- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.42+ Usually, you will return an object with the methods you want to expose.43+44+#### Returns45+46+`create` returns a React Hook with API utilities, `setState`, `getState`, `getInitialState` and47+`subscribe`, attached. It lets you return data that is based on current state, using a selector48+function. It should take a selector function as its only argument.49+50+## Usage51+52+### Updating state based on previous state53+54+To update a state based on previous state we should use **updater functions**. Read more55+about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).56+57+This example shows how you can support **updater functions** within **actions**.58+59+```tsx60+import { create } from 'zustand'61+62+type AgeStoreState = { age: number }63+64+type AgeStoreActions = {65+ setAge: (66+ nextAge:67+ | AgeStoreState['age']68+ | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),69+ ) => void70+}71+72+type AgeStore = AgeStoreState & AgeStoreActions73+74+const useAgeStore = create<AgeStore>()((set) => ({75+ age: 42,76+ setAge: (nextAge) => {77+ set((state) => ({78+ age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,79+ }))80+ },81+}))82+83+export default function App() {84+ const age = useAgeStore((state) => state.age)85+ const setAge = useAgeStore((state) => state.setAge)86+87+ function increment() {88+ setAge((currentAge) => currentAge + 1)89+ }90+91+ return (92+ <>93+ <h1>Your age: {age}</h1>94+ <button95+ onClick={() => {96+ increment()97+ increment()98+ increment()99+ }}100+ >101+ +3102+ </button>103+ <button104+ onClick={() => {105+ increment()106+ }}107+ >108+ +1109+ </button>110+ </>111+ )112+}113+```114+115+### Updating Primitives in State116+117+State can hold any kind of JavaScript value. When you want to update built-in primitive values like118+numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied119+correctly, and avoid unexpected behaviors.120+121+> [!NOTE]122+> By default, `set` function performs a shallow merge. If you need to completely replace the state123+> with a new one, use the `replace` parameter set to `true`124+125+```tsx126+import { create } from 'zustand'127+128+type XStore = number129+130+const useXStore = create<XStore>()(() => 0)131+132+export default function MovingDot() {133+ const x = useXStore()134+ const setX = (nextX: number) => {135+ useXStore.setState(nextX, true)136+ }137+ const position = { y: 0, x }138+139+ return (140+ <div141+ onPointerMove={(e) => {142+ setX(e.clientX)143+ }}144+ style={{145+ position: 'relative',146+ width: '100vw',147+ height: '100vh',148+ }}149+ >150+ <div151+ style={{152+ position: 'absolute',153+ backgroundColor: 'red',154+ borderRadius: '50%',155+ transform: `translate(${position.x}px, ${position.y}px)`,156+ left: -10,157+ top: -10,158+ width: 20,159+ height: 20,160+ }}161+ />162+ </div>163+ )164+}165+```166+167+### Updating Objects in State168+169+Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store170+them in state. Instead, when you want to update an object, you need to create a new one (or make a171+copy of an existing one), and then set the state to use the new object.172+173+By default, `set` function performs a shallow merge. For most updates where you only need to modify174+specific properties, the default shallow merge is preferred as it's more efficient. To completely175+replace the state with a new one, use the `replace` parameter set to `true` with caution, as it176+discards any existing nested data within the state.177+178+```tsx179+import { create } from 'zustand'180+181+type PositionStoreState = { position: { x: number; y: number } }182+183+type PositionStoreActions = {184+ setPosition: (nextPosition: PositionStoreState['position']) => void185+}186+187+type PositionStore = PositionStoreState & PositionStoreActions188+189+const usePositionStore = create<PositionStore>()((set) => ({190+ position: { x: 0, y: 0 },191+ setPosition: (nextPosition) => set({ position: nextPosition }),192+}))193+194+export default function MovingDot() {195+ const position = usePositionStore((state) => state.position)196+ const setPosition = usePositionStore((state) => state.setPosition)197+198+ return (199+ <div200+ onPointerMove={(e) => {201+ setPosition({202+ x: e.clientX,203+ y: e.clientY,204+ })205+ }}206+ style={{207+ position: 'relative',208+ width: '100vw',209+ height: '100vh',210+ }}211+ >212+ <div213+ style={{214+ position: 'absolute',215+ backgroundColor: 'red',216+ borderRadius: '50%',217+ transform: `translate(${position.x}px, ${position.y}px)`,218+ left: -10,219+ top: -10,220+ width: 20,221+ height: 20,222+ }}223+ />224+ </div>225+ )226+}227+```228+229+### Updating Arrays in State230+231+Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in232+state. Just like with objects, when you want to update an array stored in state, you need to create233+a new one (or make a copy of an existing one), and then set state to use the new array.234+235+By default, `set` function performs a shallow merge. To update array values we should assign new236+values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely237+replace the state with a new one, use the `replace` parameter set to `true`.238+239+> [!IMPORTANT]240+> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,241+> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid242+> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,243+> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.244+245+```tsx246+import { create } from 'zustand'247+248+type PositionStore = [number, number]249+250+const usePositionStore = create<PositionStore>()(() => [0, 0])251+252+export default function MovingDot() {253+ const [x, y] = usePositionStore()254+ const setPosition: typeof usePositionStore.setState = (nextPosition) => {255+ usePositionStore.setState(nextPosition, true)256+ }257+ const position = { x, y }258+259+ return (260+ <div261+ onPointerMove={(e) => {262+ setPosition([e.clientX, e.clientY])263+ }}264+ style={{265+ position: 'relative',266+ width: '100vw',267+ height: '100vh',268+ }}269+ >270+ <div271+ style={{272+ position: 'absolute',273+ backgroundColor: 'red',274+ borderRadius: '50%',275+ transform: `translate(${position.x}px, ${position.y}px)`,276+ left: -10,277+ top: -10,278+ width: 20,279+ height: 20,280+ }}281+ />282+ </div>283+ )284+}285+```286+287+### Updating state with no store actions288+289+Defining actions at module level, external to the store have a few advantages like: it doesn't290+require a hook to call an action, and it facilitates code splitting.291+292+> [!NOTE]293+> The recommended way is to colocate actions and states within the store (let your actions be294+> located together with your state).295+296+```tsx297+import { create } from 'zustand'298+299+const usePositionStore = create<{300+ x: number301+ y: number302+}>()(() => ({ x: 0, y: 0 }))303+304+const setPosition: typeof usePositionStore.setState = (nextPosition) => {305+ usePositionStore.setState(nextPosition)306+}307+308+export default function MovingDot() {309+ const position = usePositionStore()310+311+ return (312+ <div313+ style={{314+ position: 'relative',315+ width: '100vw',316+ height: '100vh',317+ }}318+ >319+ <div320+ style={{321+ position: 'absolute',322+ backgroundColor: 'red',323+ borderRadius: '50%',324+ transform: `translate(${position.x}px, ${position.y}px)`,325+ left: -10,326+ top: -10,327+ width: 20,328+ height: 20,329+ }}330+ onMouseEnter={(event) => {331+ const parent = event.currentTarget.parentElement332+ const parentWidth = parent.clientWidth333+ const parentHeight = parent.clientHeight334+335+ setPosition({336+ x: Math.ceil(Math.random() * parentWidth),337+ y: Math.ceil(Math.random() * parentHeight),338+ })339+ }}340+ />341+ </div>342+ )343+}344+```345+346+### Subscribing to state updates347+348+By subscribing to state updates, you register a callback that fires whenever the store's state349+updates. We can use `subscribe` for external state management.350+351+```tsx352+import { useEffect } from 'react'353+import { create } from 'zustand'354+355+type PositionStoreState = { position: { x: number; y: number } }356+357+type PositionStoreActions = {358+ setPosition: (nextPosition: PositionStoreState['position']) => void359+}360+361+type PositionStore = PositionStoreState & PositionStoreActions362+363+const usePositionStore = create<PositionStore>()((set) => ({364+ position: { x: 0, y: 0 },365+ setPosition: (nextPosition) => set({ position: nextPosition }),366+}))367+368+export default function MovingDot() {369+ const position = usePositionStore((state) => state.position)370+ const setPosition = usePositionStore((state) => state.setPosition)371+372+ useEffect(() => {373+ const unsubscribePositionStore = usePositionStore.subscribe(374+ ({ position }) => {375+ console.log('new position', { position })376+ },377+ )378+379+ return () => {380+ unsubscribePositionStore()381+ }382+ }, [])383+384+ return (385+ <div386+ style={{387+ position: 'relative',388+ width: '100vw',389+ height: '100vh',390+ }}391+ >392+ <div393+ style={{394+ position: 'absolute',395+ backgroundColor: 'red',396+ borderRadius: '50%',397+ transform: `translate(${position.x}px, ${position.y}px)`,398+ left: -10,399+ top: -10,400+ width: 20,401+ height: 20,402+ }}403+ onMouseEnter={(event) => {404+ const parent = event.currentTarget.parentElement405+ const parentWidth = parent.clientWidth406+ const parentHeight = parent.clientHeight407+408+ setPosition({409+ x: Math.ceil(Math.random() * parentWidth),410+ y: Math.ceil(Math.random() * parentHeight),411+ })412+ }}413+ />414+ </div>415+ )416+}417+```418+419+## Troubleshooting420+421+### I’ve updated the state, but the screen doesn’t update422+423+In the previous example, the `position` object is always created fresh from the current cursor424+position. But often, you will want to include existing data as a part of the new object you’re425+creating. For example, you may want to update only one field in a form, but keep the previous426+values for all other fields.427+428+These input fields don’t work because the `onChange` handlers mutate the state:429+430+```tsx431+import { create } from 'zustand'432+433+type PersonStoreState = {434+ firstName: string435+ lastName: string436+ email: string437+}438+439+type PersonStoreActions = {440+ setPerson: (nextPerson: Partial<PersonStoreState>) => void441+}442+443+type PersonStore = PersonStoreState & PersonStoreActions444+445+const usePersonStore = create<PersonStore>()((set) => ({446+ firstName: 'Barbara',447+ lastName: 'Hepworth',448+ email: 'bhepworth@sculpture.com',449+ setPerson: (nextPerson) => set(nextPerson),450+}))451+452+export default function Form() {453+ const person = usePersonStore((state) => state)454+ const setPerson = usePersonStore((state) => state.setPerson)455+456+ function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {457+ person.firstName = e.target.value458+ }459+460+ function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {461+ person.lastName = e.target.value462+ }463+464+ function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {465+ person.email = e.target.value466+ }467+468+ return (469+ <>470+ <label style={{ display: 'block' }}>471+ First name:472+ <input value={person.firstName} onChange={handleFirstNameChange} />473+ </label>474+ <label style={{ display: 'block' }}>475+ Last name:476+ <input value={person.lastName} onChange={handleLastNameChange} />477+ </label>478+ <label style={{ display: 'block' }}>479+ Email:480+ <input value={person.email} onChange={handleEmailChange} />481+ </label>482+ <p>483+ {person.firstName} {person.lastName} ({person.email})484+ </p>485+ </>486+ )487+}488+```489+490+For example, this line mutates the state from a past render:491+492+```tsx493+person.firstName = e.target.value494+```495+496+The reliable way to get the behavior you’re looking for is to create a new object and pass it to497+`setPerson`. But here you want to also copy the existing data into it because only one of the498+fields has changed:499+500+```ts501+setPerson({ ...person, firstName: e.target.value }) // New first name from the input502+```503+504+> [!NOTE]505+> We don’t need to copy every property separately due to `set` function performing shallow merge by506+> default.507+508+Now the form works!509+510+Notice how you didn’t declare a separate state variable for each input field. For large forms,511+keeping all data grouped in an object is very convenient—as long as you update it correctly!512+513+```tsx {27,31,35}514+import { create } from 'zustand'515+516+type PersonStoreState = {517+ person: { firstName: string; lastName: string; email: string }518+}519+520+type PersonStoreActions = {521+ setPerson: (nextPerson: PersonStoreState['person']) => void522+}523+524+type PersonStore = PersonStoreState & PersonStoreActions525+526+const usePersonStore = create<PersonStore>()((set) => ({527+ person: {528+ firstName: 'Barbara',529+ lastName: 'Hepworth',530+ email: 'bhepworth@sculpture.com',531+ },532+ setPerson: (nextPerson) => set(nextPerson),533+}))534+535+export default function Form() {536+ const person = usePersonStore((state) => state.person)537+ const setPerson = usePersonStore((state) => state.setPerson)538+539+ function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {540+ setPerson({ ...person, firstName: e.target.value })541+ }542+543+ function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {544+ setPerson({ ...person, lastName: e.target.value })545+ }546+547+ function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {548+ setPerson({ ...person, email: e.target.value })549+ }550+551+ return (552+ <>553+ <label style={{ display: 'block' }}>554+ First name:555+ <input value={person.firstName} onChange={handleFirstNameChange} />556+ </label>557+ <label style={{ display: 'block' }}>558+ Last name:559+ <input value={person.lastName} onChange={handleLastNameChange} />560+ </label>561+ <label style={{ display: 'block' }}>562+ Email:563+ <input value={person.email} onChange={handleEmailChange} />564+ </label>565+ <p>566+ {person.firstName} {person.lastName} ({person.email})567+ </p>568+ </>569+ )570+}571+```added:docs/reference/apis/shallow.md+248 added
1+---2+title: shallow3+description: How compare simple data effectively4+nav: 245+---6+7+`shallow` lets you run fast checks on simple data structures. It effectively identifies changes in8+**top-level** properties when you're working with data structures that don't have nested objects or9+arrays within them.10+11+> [!NOTE]12+> Shallow lets you perform quick comparisons, but keep its limitations in mind.13+14+```js15+const equal = shallow(a, b)16+```17+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+ - [Comparing objects with different prototypes](#comparing-objects-with-different-prototypes)29+30+## Types31+32+### Signature33+34+```ts35+shallow<T>(a: T, b: T): boolean36+```37+38+## Reference39+40+### `shallow(a, b)`41+42+#### Parameters43+44+- `a`: The first value.45+- `b`: The second value.46+47+#### Returns48+49+`shallow` returns `true` when `a` and `b` are equal based on a shallow comparison of their50+**top-level** properties. Otherwise, it should return `false`.51+52+## Usage53+54+### Comparing Primitives55+56+When comparing primitive values like `string`s, `number`s, `boolean`s, and `BigInt`s, both57+`Object.is` and `shallow` function return `true` if the values are the same. This is because58+primitive values are compared by their actual value rather than by reference.59+60+```ts61+const stringLeft = 'John Doe'62+const stringRight = 'John Doe'63+64+Object.is(stringLeft, stringRight) // -> true65+shallow(stringLeft, stringRight) // -> true66+67+const numberLeft = 1068+const numberRight = 1069+70+Object.is(numberLeft, numberRight) // -> true71+shallow(numberLeft, numberRight) // -> true72+73+const booleanLeft = true74+const booleanRight = true75+76+Object.is(booleanLeft, booleanRight) // -> true77+shallow(booleanLeft, booleanRight) // -> true78+79+const bigIntLeft = 1n80+const bigIntRight = 1n81+82+Object.is(bigIntLeft, bigIntRight) // -> true83+shallow(bigIntLeft, bigIntRight) // -> true84+```85+86+### Comparing Objects87+88+When comparing objects, it's important to understand how `Object.is` and `shallow` function89+operate, as they handle comparisons differently.90+91+The `shallow` function returns `true` because shallow performs a shallow comparison of the objects.92+It checks if the top-level properties and their values are the same. In this case, the top-level93+properties (`firstName`, `lastName`, and `age`) and their values are identical between `objectLeft`94+and `objectRight`, so shallow considers them equal.95+96+```ts97+const objectLeft = {98+ firstName: 'John',99+ lastName: 'Doe',100+ age: 30,101+}102+const objectRight = {103+ firstName: 'John',104+ lastName: 'Doe',105+ age: 30,106+}107+108+Object.is(objectLeft, objectRight) // -> false109+shallow(objectLeft, objectRight) // -> true110+```111+112+### Comparing Sets113+114+When comparing sets, it's important to understand how `Object.is` and `shallow` function operate,115+as they handle comparisons differently.116+117+The `shallow` function returns `true` because shallow performs a shallow comparison of the sets. It118+checks if the top-level properties (in this case, the sets themselves) are the same. Since `setLeft`119+and `setRight` are both instances of the Set object and contain the same elements, shallow considers120+them equal.121+122+```ts123+const setLeft = new Set([1, 2, 3])124+const setRight = new Set([1, 2, 3])125+126+Object.is(setLeft, setRight) // -> false127+shallow(setLeft, setRight) // -> true128+```129+130+### Comparing Maps131+132+When comparing maps, it's important to understand how `Object.is` and `shallow` function operate, as133+they handle comparisons differently.134+135+The `shallow` returns `true` because shallow performs a shallow comparison of the maps. It checks if136+the top-level properties (in this case, the maps themselves) are the same. Since `mapLeft` and137+`mapRight` are both instances of the Map object and contain the same key-value pairs, shallow138+considers them equal.139+140+```ts141+const mapLeft = new Map([142+ [1, 'one'],143+ [2, 'two'],144+ [3, 'three'],145+])146+const mapRight = new Map([147+ [1, 'one'],148+ [2, 'two'],149+ [3, 'three'],150+])151+152+Object.is(mapLeft, mapRight) // -> false153+shallow(mapLeft, mapRight) // -> true154+```155+156+## Troubleshooting157+158+### Comparing objects returns `false` even if they are identical.159+160+The `shallow` function performs a shallow comparison. A shallow comparison checks if the top-level161+properties of two objects are equal. It does not check nested objects or deeply nested properties.162+In other words, it only compares the references of the properties.163+164+In the following example, the shallow function returns `false` because it compares only the165+top-level properties and their references. The address property in both objects is a nested object,166+and even though their contents are identical, their references are different. Consequently, shallow167+sees them as different, resulting in `false`.168+169+```ts170+const objectLeft = {171+ firstName: 'John',172+ lastName: 'Doe',173+ age: 30,174+ address: {175+ street: 'Kulas Light',176+ suite: 'Apt. 556',177+ city: 'Gwenborough',178+ zipcode: '92998-3874',179+ geo: {180+ lat: '-37.3159',181+ lng: '81.1496',182+ },183+ },184+}185+const objectRight = {186+ firstName: 'John',187+ lastName: 'Doe',188+ age: 30,189+ address: {190+ street: 'Kulas Light',191+ suite: 'Apt. 556',192+ city: 'Gwenborough',193+ zipcode: '92998-3874',194+ geo: {195+ lat: '-37.3159',196+ lng: '81.1496',197+ },198+ },199+}200+201+Object.is(objectLeft, objectRight) // -> false202+shallow(objectLeft, objectRight) // -> false203+```204+205+If we remove the `address` property, the shallow comparison would work as expected because all206+top-level properties would be primitive values or references to the same values:207+208+```ts209+const objectLeft = {210+ firstName: 'John',211+ lastName: 'Doe',212+ age: 30,213+}214+const objectRight = {215+ firstName: 'John',216+ lastName: 'Doe',217+ age: 30,218+}219+220+Object.is(objectLeft, objectRight) // -> false221+shallow(objectLeft, objectRight) // -> true222+```223+224+In this modified example, `objectLeft` and `objectRight` have the same top-level properties and225+primitive values. Since `shallow` function only compares the top-level properties, it will return226+`true` because the primitive values (`firstName`, `lastName`, and `age`) are identical in both227+objects.228+229+### Comparing objects with different prototypes230+231+The `shallow` function checks whether the two objects have the same prototype. If their prototypes232+are referentially different, shallow will return `false`. This comparison is done using:233+234+```ts235+Object.getPrototypeOf(a) === Object.getPrototypeOf(b)236+```237+238+> [!IMPORTANT]239+> Objects created with the object initializer (`{}`) or with `new Object()` inherit from240+> `Object.prototype` by default. However, objects created with `Object.create(proto)` inherit from241+> the proto you pass in—which may not be `Object.prototype.`242+243+```ts244+const a = Object.create({}) // -> prototype is `{}`245+const b = {} // -> prototype is `Object.prototype`246+247+shallow(a, b) // -> false248+```added:docs/reference/hooks/use-shallow.md+267 added
1+---2+title: useShallow3+description: How to memoize selector functions4+tag: react5+nav: 276+---7+8+`useShallow` is a React Hook that lets you optimize re-renders.9+10+```js11+const memoizedSelector = useShallow(selector)12+```13+14+- [Types](#types)15+ - [Signature](#signature)16+- [Reference](#reference)17+- [Usage](#usage)18+ - [Writing a memoized selector](#writing-a-memoized-selector)19+- [Troubleshooting](#troubleshooting)20+21+### Signature22+23+```ts24+useShallow<T, U = T>(selectorFn: (state: T) => U): (state: T) => U25+```26+27+## Reference28+29+### `useShallow(selectorFn)`30+31+#### Parameters32+33+- `selectorFn`: A function that lets you return data that is based on current state.34+35+#### Returns36+37+`useShallow` returns a memoized version of a selector function using a shallow comparison for38+memoization.39+40+## Usage41+42+### Writing a memoized selector43+44+First, we need to setup a store to hold the state for the bear family. In this store, we define45+three properties: `papaBear`, `mamaBear`, and `babyBear`, each representing a different member of46+the bear family and their respective oatmeal pot sizes.47+48+```tsx49+import { create } from 'zustand'50+51+type BearFamilyMealsStore = {52+ [key: string]: string53+}54+55+const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({56+ papaBear: 'large porridge-pot',57+ mamaBear: 'middle-size porridge pot',58+ babyBear: 'A little, small, wee pot',59+}))60+```61+62+Next, we'll create a `BearNames` component that retrieves the keys of our state (the bear family63+members) and displays them.64+65+```tsx66+function BearNames() {67+ const names = useBearFamilyMealsStore((state) => Object.keys(state))68+69+ return <div>{names.join(', ')}</div>70+}71+```72+73+Next, we will create a `UpdateBabyBearMeal` component that periodically updates baby bear's meal74+choice.75+76+```tsx77+const meals = [78+ 'A tiny, little, wee bowl',79+ 'A small, petite, tiny pot',80+ 'A wee, itty-bitty, small bowl',81+ 'A little, petite, tiny dish',82+ 'A tiny, small, wee vessel',83+ 'A small, little, wee cauldron',84+ 'A little, tiny, small cup',85+ 'A wee, small, little jar',86+ 'A tiny, wee, small pan',87+ 'A small, wee, little crock',88+]89+90+function UpdateBabyBearMeal() {91+ useEffect(() => {92+ const timer = setInterval(() => {93+ useBearFamilyMealsStore.setState({94+ babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],95+ })96+ }, 1000)97+98+ return () => {99+ clearInterval(timer)100+ }101+ }, [])102+103+ return null104+}105+```106+107+Finally, we combine both components in the `App` component to see them in action.108+109+```tsx110+export default function App() {111+ return (112+ <>113+ <UpdateBabyBearMeal />114+ <BearNames />115+ </>116+ )117+}118+```119+120+Here is what the code should look like:121+122+```tsx123+import { useEffect } from 'react'124+import { create } from 'zustand'125+126+type BearFamilyMealsStore = {127+ [key: string]: string128+}129+130+const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({131+ papaBear: 'large porridge-pot',132+ mamaBear: 'middle-size porridge pot',133+ babyBear: 'A little, small, wee pot',134+}))135+136+const meals = [137+ 'A tiny, little, wee bowl',138+ 'A small, petite, tiny pot',139+ 'A wee, itty-bitty, small bowl',140+ 'A little, petite, tiny dish',141+ 'A tiny, small, wee vessel',142+ 'A small, little, wee cauldron',143+ 'A little, tiny, small cup',144+ 'A wee, small, little jar',145+ 'A tiny, wee, small pan',146+ 'A small, wee, little crock',147+]148+149+function UpdateBabyBearMeal() {150+ useEffect(() => {151+ const timer = setInterval(() => {152+ useBearFamilyMealsStore.setState({153+ babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],154+ })155+ }, 1000)156+157+ return () => {158+ clearInterval(timer)159+ }160+ }, [])161+162+ return null163+}164+165+function BearNames() {166+ const names = useBearFamilyMealsStore((state) => Object.keys(state))167+168+ return <div>{names.join(', ')}</div>169+}170+171+export default function App() {172+ return (173+ <>174+ <UpdateBabyBearMeal />175+ <BearNames />176+ </>177+ )178+}179+```180+181+Everything might look fine, but there’s a small problem: the `BearNames` component keeps182+re-rendering even if the names haven’t changed. This happens because the component re-renders183+whenever any part of the state changes, even if the specific part we care about (the list of names) hasn’t changed.184+185+To fix this, we use `useShallow` to make sure the component only re-renders when the actual keys of186+the state change:187+188+```tsx189+function BearNames() {190+ const names = useBearFamilyMealsStore(191+ useShallow((state) => Object.keys(state)),192+ )193+194+ return <div>{names.join(', ')}</div>195+}196+```197+198+Here is what the code should look like:199+200+```tsx201+import { useEffect } from 'react'202+import { create } from 'zustand'203+import { useShallow } from 'zustand/react/shallow'204+205+type BearFamilyMealsStore = {206+ [key: string]: string207+}208+209+const useBearFamilyMealsStore = create<BearFamilyMealsStore>()(() => ({210+ papaBear: 'large porridge-pot',211+ mamaBear: 'middle-size porridge pot',212+ babyBear: 'A little, small, wee pot',213+}))214+215+const meals = [216+ 'A tiny, little, wee bowl',217+ 'A small, petite, tiny pot',218+ 'A wee, itty-bitty, small bowl',219+ 'A little, petite, tiny dish',220+ 'A tiny, small, wee vessel',221+ 'A small, little, wee cauldron',222+ 'A little, tiny, small cup',223+ 'A wee, small, little jar',224+ 'A tiny, wee, small pan',225+ 'A small, wee, little crock',226+]227+228+function UpdateBabyBearMeal() {229+ useEffect(() => {230+ const timer = setInterval(() => {231+ useBearFamilyMealsStore.setState({232+ babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],233+ })234+ }, 1000)235+236+ return () => {237+ clearInterval(timer)238+ }239+ }, [])240+241+ return null242+}243+244+function BearNames() {245+ const names = useBearFamilyMealsStore(246+ useShallow((state) => Object.keys(state)),247+ )248+249+ return <div>{names.join(', ')}</div>250+}251+252+export default function App() {253+ return (254+ <>255+ <UpdateBabyBearMeal />256+ <BearNames />257+ </>258+ )259+}260+```261+262+By using `useShallow`, we optimized the rendering process, ensuring that the component only263+re-renders when necessary, which improves overall performance.264+265+## Troubleshooting266+267+TBDadded:docs/reference/hooks/use-store-with-equality-fn.md+957 added
1+---2+title: useStoreWithEqualityFn3+description: How to use vanilla stores effectively in React4+tag: react5+nav: 266+---7+8+`useStoreWithEqualityFn` is a React Hook that lets you use a vanilla store in React, just like9+`useStore`. However, it offers a way to define a custom equality check. This allows for more10+granular control over when components re-render, improving performance and responsiveness.11+12+> [!IMPORTANT]13+> In order to use `useStoreWithEqualityFn` from `zustand/traditional` you need to install14+> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.15+16+```js17+const someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)18+```19+20+- [Types](#types)21+ - [Signature](#signature)22+- [Reference](#reference)23+- [Usage](#usage)24+ - [Using a global vanilla store in React](#using-a-global-vanilla-store-in-react)25+ - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)26+ - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)27+ - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)28+- [Troubleshooting](#troubleshooting)29+30+### Signature31+32+```ts33+useStoreWithEqualityFn<T, U = T>(store: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: T, b: T) => boolean): U34+```35+36+## Reference37+38+### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`39+40+#### Parameters41+42+- `storeApi`: The instance that lets you access to store API utilities.43+- `selectorFn`: A function that lets you return data that is based on current state.44+- `equalityFn`: A function that lets you skip re-renders.45+46+#### Returns47+48+`useStoreWithEqualityFn` returns any data based on current state depending on the selector function,49+and lets you skip re-renders using an equality function. It should take a store, a selector50+function, and an equality function as arguments.51+52+## Usage53+54+### Using a global vanilla store in React55+56+First, let's set up a store that will hold the position of the dot on the screen. We'll define the57+store to manage `x` and `y` coordinates and provide an action to update these coordinates.58+59+```tsx60+import { createStore, useStore } from 'zustand'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>()((set) => ({71+ position: { x: 0, y: 0 },72+ setPosition: (position) => set({ position }),73+}))74+```75+76+Next, we'll create a `MovingDot` component that renders a div representing the dot. This component77+will use the store to track and update the dot's position.78+79+```tsx80+function MovingDot() {81+ const position = useStoreWithEqualityFn(82+ positionStore,83+ (state) => state.position,84+ shallow,85+ )86+ const setPosition = useStoreWithEqualityFn(87+ positionStore,88+ (state) => state.setPosition,89+ shallow,90+ )91+92+ return (93+ <div94+ onPointerMove={(e) => {95+ setPosition({96+ x: e.clientX,97+ y: e.clientY,98+ })99+ }}100+ style={{101+ position: 'relative',102+ width: '100vw',103+ height: '100vh',104+ }}105+ >106+ <div107+ style={{108+ position: 'absolute',109+ backgroundColor: 'red',110+ borderRadius: '50%',111+ transform: `translate(${position.x}px, ${position.y}px)`,112+ left: -10,113+ top: -10,114+ width: 20,115+ height: 20,116+ }}117+ />118+ </div>119+ )120+}121+```122+123+Finally, we’ll render the `MovingDot` component in our `App` component.124+125+```tsx126+export default function App() {127+ return <MovingDot />128+}129+```130+131+Here is what the code should look like:132+133+```tsx134+import { createStore } from 'zustand'135+import { useStoreWithEqualityFn } from 'zustand/traditional'136+import { shallow } from 'zustand/shallow'137+138+type PositionStoreState = { position: { x: number; y: number } }139+140+type PositionStoreActions = {141+ setPosition: (nextPosition: PositionStoreState['position']) => void142+}143+144+type PositionStore = PositionStoreState & PositionStoreActions145+146+const positionStore = createStore<PositionStore>()((set) => ({147+ position: { x: 0, y: 0 },148+ setPosition: (position) => set({ position }),149+}))150+151+function MovingDot() {152+ const position = useStoreWithEqualityFn(153+ positionStore,154+ (state) => state.position,155+ shallow,156+ )157+ const setPosition = useStoreWithEqualityFn(158+ positionStore,159+ (state) => state.setPosition,160+ shallow,161+ )162+163+ return (164+ <div165+ onPointerMove={(e) => {166+ setPosition({167+ x: e.clientX,168+ y: e.clientY,169+ })170+ }}171+ style={{172+ position: 'relative',173+ width: '100vw',174+ height: '100vh',175+ }}176+ >177+ <div178+ style={{179+ position: 'absolute',180+ backgroundColor: 'red',181+ borderRadius: '50%',182+ transform: `translate(${position.x}px, ${position.y}px)`,183+ left: -10,184+ top: -10,185+ width: 20,186+ height: 20,187+ }}188+ />189+ </div>190+ )191+}192+193+export default function App() {194+ return <MovingDot />195+}196+```197+198+### Using dynamic global vanilla stores in React199+200+First, we'll create a factory function that generates a store for managing the counter state.201+Each tab will have its own instance of this store.202+203+```ts204+import { createStore } from 'zustand'205+206+type CounterState = {207+ count: number208+}209+210+type CounterActions = { increment: () => void }211+212+type CounterStore = CounterState & CounterActions213+214+const createCounterStore = () => {215+ return createStore<CounterStore>()((set) => ({216+ count: 0,217+ increment: () => {218+ set((state) => ({ count: state.count + 1 }))219+ },220+ }))221+}222+```223+224+Next, we'll create a factory function that manages the creation and retrieval of counter stores.225+This allows each tab to have its own independent counter.226+227+```ts228+const defaultCounterStores = new Map<229+ string,230+ ReturnType<typeof createCounterStore>231+>()232+233+const createCounterStoreFactory = (234+ counterStores: typeof defaultCounterStores,235+) => {236+ return (counterStoreKey: string) => {237+ if (!counterStores.has(counterStoreKey)) {238+ counterStores.set(counterStoreKey, createCounterStore())239+ }240+ return counterStores.get(counterStoreKey)!241+ }242+}243+244+const getOrCreateCounterStoreByKey =245+ createCounterStoreFactory(defaultCounterStores)246+```247+248+Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s249+counter.250+251+```tsx252+const [currentTabIndex, setCurrentTabIndex] = useState(0)253+const counterState = useStoreWithEqualityFn(254+ getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),255+ (state) => state,256+ shallow,257+)258+259+return (260+ <div style={{ fontFamily: 'monospace' }}>261+ <div262+ style={{263+ display: 'flex',264+ gap: '0.5rem',265+ borderBottom: '1px solid salmon',266+ paddingBottom: 4,267+ }}268+ >269+ <button270+ type="button"271+ style={{272+ border: '1px solid salmon',273+ backgroundColor: '#fff',274+ cursor: 'pointer',275+ }}276+ onClick={() => setCurrentTabIndex(0)}277+ >278+ Tab 1279+ </button>280+ <button281+ type="button"282+ style={{283+ border: '1px solid salmon',284+ backgroundColor: '#fff',285+ cursor: 'pointer',286+ }}287+ onClick={() => setCurrentTabIndex(1)}288+ >289+ Tab 2290+ </button>291+ <button292+ type="button"293+ style={{294+ border: '1px solid salmon',295+ backgroundColor: '#fff',296+ cursor: 'pointer',297+ }}298+ onClick={() => setCurrentTabIndex(2)}299+ >300+ Tab 3301+ </button>302+ </div>303+ <div style={{ padding: 4 }}>304+ Content of Tab {currentTabIndex + 1}305+ <br /> <br />306+ <button type="button" onClick={() => counterState.increment()}>307+ Count: {counterState.count}308+ </button>309+ </div>310+ </div>311+)312+```313+314+Finally, we'll create the `App` component, which renders the tabs and their respective counters.315+The counter state is managed independently for each tab.316+317+```tsx318+export default function App() {319+ return <Tabs />320+}321+```322+323+Here is what the code should look like:324+325+```tsx326+import { useState } from 'react'327+import { createStore } from 'zustand'328+import { useStoreWithEqualityFn } from 'zustand/traditional'329+import { shallow } from 'zustand/shallow'330+331+type CounterState = {332+ count: number333+}334+335+type CounterActions = { increment: () => void }336+337+type CounterStore = CounterState & CounterActions338+339+const createCounterStore = () => {340+ return createStore<CounterStore>()((set) => ({341+ count: 0,342+ increment: () => {343+ set((state) => ({ count: state.count + 1 }))344+ },345+ }))346+}347+348+const defaultCounterStores = new Map<349+ string,350+ ReturnType<typeof createCounterStore>351+>()352+353+const createCounterStoreFactory = (354+ counterStores: typeof defaultCounterStores,355+) => {356+ return (counterStoreKey: string) => {357+ if (!counterStores.has(counterStoreKey)) {358+ counterStores.set(counterStoreKey, createCounterStore())359+ }360+ return counterStores.get(counterStoreKey)!361+ }362+}363+364+const getOrCreateCounterStoreByKey =365+ createCounterStoreFactory(defaultCounterStores)366+367+export default function App() {368+ const [currentTabIndex, setCurrentTabIndex] = useState(0)369+ const counterState = useStoreWithEqualityFn(370+ getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),371+ (state) => state,372+ shallow,373+ )374+375+ return (376+ <div style={{ fontFamily: 'monospace' }}>377+ <div378+ style={{379+ display: 'flex',380+ gap: '0.5rem',381+ borderBottom: '1px solid salmon',382+ paddingBottom: 4,383+ }}384+ >385+ <button386+ type="button"387+ style={{388+ border: '1px solid salmon',389+ backgroundColor: '#fff',390+ cursor: 'pointer',391+ }}392+ onClick={() => setCurrentTabIndex(0)}393+ >394+ Tab 1395+ </button>396+ <button397+ type="button"398+ style={{399+ border: '1px solid salmon',400+ backgroundColor: '#fff',401+ cursor: 'pointer',402+ }}403+ onClick={() => setCurrentTabIndex(1)}404+ >405+ Tab 2406+ </button>407+ <button408+ type="button"409+ style={{410+ border: '1px solid salmon',411+ backgroundColor: '#fff',412+ cursor: 'pointer',413+ }}414+ onClick={() => setCurrentTabIndex(2)}415+ >416+ Tab 3417+ </button>418+ </div>419+ <div style={{ padding: 4 }}>420+ Content of Tab {currentTabIndex + 1}421+ <br /> <br />422+ <button type="button" onClick={() => counterState.increment()}>423+ Count: {counterState.count}424+ </button>425+ </div>426+ </div>427+ )428+}429+```430+431+### Using scoped (non-global) vanilla store in React432+433+First, let's set up a store that will hold the position of the dot on the screen. We'll define the434+store to manage `x` and `y` coordinates and provide an action to update these coordinates.435+436+```tsx437+type PositionStoreState = { position: { x: number; y: number } }438+439+type PositionStoreActions = {440+ setPosition: (nextPosition: PositionStoreState['position']) => void441+}442+443+type PositionStore = PositionStoreState & PositionStoreActions444+445+const createPositionStore = () => {446+ return createStore<PositionStore>()((set) => ({447+ position: { x: 0, y: 0 },448+ setPosition: (position) => set({ position }),449+ }))450+}451+```452+453+Next, we'll create a context and a provider component to pass down the store through the React454+component tree. This allows each `MovingDot` component to have its own independent state.455+456+```tsx457+const PositionStoreContext = createContext<ReturnType<458+ typeof createPositionStore459+> | null>(null)460+461+function PositionStoreProvider({ children }: { children: ReactNode }) {462+ const [store] = useState(() => createPositionStore())463+ return (464+ <PositionStoreContext.Provider value={store}>465+ {children}466+ </PositionStoreContext.Provider>467+ )468+}469+```470+471+To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook472+will read the store from the context and allow us to select specific parts of the state.473+474+```ts475+function usePositionStore<U>(selector: (state: PositionStore) => U) {476+ const store = useContext(PositionStoreContext)477+478+ if (store === null) {479+ throw new Error(480+ 'usePositionStore must be used within PositionStoreProvider',481+ )482+ }483+484+ return useStoreWithEqualityFn(store, selector, shallow)485+}486+```487+488+Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor489+within its container.490+491+```tsx492+function MovingDot({ color }: { color: string }) {493+ const position = usePositionStore((state) => state.position)494+ const setPosition = usePositionStore((state) => state.setPosition)495+496+ return (497+ <div498+ onPointerMove={(e) => {499+ setPosition({500+ x:501+ e.clientX > e.currentTarget.clientWidth502+ ? e.clientX - e.currentTarget.clientWidth503+ : e.clientX,504+ y: e.clientY,505+ })506+ }}507+ style={{508+ position: 'relative',509+ width: '50vw',510+ height: '100vh',511+ }}512+ >513+ <div514+ style={{515+ position: 'absolute',516+ backgroundColor: color,517+ borderRadius: '50%',518+ transform: `translate(${position.x}px, ${position.y}px)`,519+ left: -10,520+ top: -10,521+ width: 20,522+ height: 20,523+ }}524+ />525+ </div>526+ )527+}528+```529+530+Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`531+components, each with its own independent state.532+533+```tsx534+export default function App() {535+ return (536+ <div style={{ display: 'flex' }}>537+ <PositionStoreProvider>538+ <MovingDot color="red" />539+ </PositionStoreProvider>540+ <PositionStoreProvider>541+ <MovingDot color="blue" />542+ </PositionStoreProvider>543+ </div>544+ )545+}546+```547+548+Here is what the code should look like:549+550+```tsx551+import { type ReactNode, useState, createContext, useContext } from 'react'552+import { createStore } from 'zustand'553+import { useStoreWithEqualityFn } from 'zustand/traditional'554+import { shallow } from 'zustand/shallow'555+556+type PositionStoreState = { position: { x: number; y: number } }557+558+type PositionStoreActions = {559+ setPosition: (nextPosition: PositionStoreState['position']) => void560+}561+562+type PositionStore = PositionStoreState & PositionStoreActions563+564+const createPositionStore = () => {565+ return createStore<PositionStore>()((set) => ({566+ position: { x: 0, y: 0 },567+ setPosition: (position) => set({ position }),568+ }))569+}570+571+const PositionStoreContext = createContext<ReturnType<572+ typeof createPositionStore573+> | null>(null)574+575+function PositionStoreProvider({ children }: { children: ReactNode }) {576+ const [store] = useState(() => createPositionStore())577+ return (578+ <PositionStoreContext.Provider value={store}>579+ {children}580+ </PositionStoreContext.Provider>581+ )582+}583+584+function usePositionStore<U>(selector: (state: PositionStore) => U) {585+ const store = useContext(PositionStoreContext)586+587+ if (store === null) {588+ throw new Error(589+ 'usePositionStore must be used within PositionStoreProvider',590+ )591+ }592+593+ return useStoreWithEqualityFn(store, selector, shallow)594+}595+596+function MovingDot({ color }: { color: string }) {597+ const position = usePositionStore((state) => state.position)598+ const setPosition = usePositionStore((state) => state.setPosition)599+600+ return (601+ <div602+ onPointerMove={(e) => {603+ setPosition({604+ x:605+ e.clientX > e.currentTarget.clientWidth606+ ? e.clientX - e.currentTarget.clientWidth607+ : e.clientX,608+ y: e.clientY,609+ })610+ }}611+ style={{612+ position: 'relative',613+ width: '50vw',614+ height: '100vh',615+ }}616+ >617+ <div618+ style={{619+ position: 'absolute',620+ backgroundColor: color,621+ borderRadius: '50%',622+ transform: `translate(${position.x}px, ${position.y}px)`,623+ left: -10,624+ top: -10,625+ width: 20,626+ height: 20,627+ }}628+ />629+ </div>630+ )631+}632+633+export default function App() {634+ return (635+ <div style={{ display: 'flex' }}>636+ <PositionStoreProvider>637+ <MovingDot color="red" />638+ </PositionStoreProvider>639+ <PositionStoreProvider>640+ <MovingDot color="blue" />641+ </PositionStoreProvider>642+ </div>643+ )644+}645+```646+647+### Using dynamic scoped (non-global) vanilla stores in React648+649+First, we'll create a factory function that generates a store for managing the counter state.650+Each tab will have its own instance of this store.651+652+```ts653+type CounterState = {654+ count: number655+}656+657+type CounterActions = { increment: () => void }658+659+type CounterStore = CounterState & CounterActions660+661+const createCounterStore = () => {662+ return createStore<CounterStore>()((set) => ({663+ count: 0,664+ increment: () => {665+ set((state) => ({ count: state.count + 1 }))666+ },667+ }))668+}669+```670+671+Next, we'll create a factory function that manages the creation and retrieval of counter stores.672+This allows each tab to have its own independent counter.673+674+```ts675+const createCounterStoreFactory = (676+ counterStores: Map<string, ReturnType<typeof createCounterStore>>,677+) => {678+ return (counterStoreKey: string) => {679+ if (!counterStores.has(counterStoreKey)) {680+ counterStores.set(counterStoreKey, createCounterStore())681+ }682+ return counterStores.get(counterStoreKey)!683+ }684+}685+```686+687+Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context688+for this.689+690+```tsx691+const CounterStoresContext = createContext(null)692+693+const CounterStoresProvider = ({ children }) => {694+ const [stores] = useState(695+ () => new Map<string, ReturnType<typeof createCounterStore>>(),696+ )697+698+ return (699+ <CounterStoresContext.Provider value={stores}>700+ {children}701+ </CounterStoresContext.Provider>702+ )703+}704+```705+706+Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a707+given tab.708+709+```tsx710+const useCounterStore = <U,>(711+ key: string,712+ selector: (state: CounterStore) => U,713+) => {714+ const stores = useContext(CounterStoresContext)715+716+ if (stores === undefined) {717+ throw new Error('useCounterStore must be used within CounterStoresProvider')718+ }719+720+ const getOrCreateCounterStoreByKey = useCallback(721+ (key: string) => createCounterStoreFactory(stores!)(key),722+ [stores],723+ )724+725+ return useStore(getOrCreateCounterStoreByKey(key), selector)726+}727+```728+729+Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s730+counter.731+732+```tsx733+function Tabs() {734+ const [currentTabIndex, setCurrentTabIndex] = useState(0)735+ const counterState = useCounterStore(736+ `tab-${currentTabIndex}`,737+ (state) => state,738+ )739+740+ return (741+ <div style={{ fontFamily: 'monospace' }}>742+ <div743+ style={{744+ display: 'flex',745+ gap: '0.5rem',746+ borderBottom: '1px solid salmon',747+ paddingBottom: 4,748+ }}749+ >750+ <button751+ type="button"752+ style={{753+ border: '1px solid salmon',754+ backgroundColor: '#fff',755+ cursor: 'pointer',756+ }}757+ onClick={() => setCurrentTabIndex(0)}758+ >759+ Tab 1760+ </button>761+ <button762+ type="button"763+ style={{764+ border: '1px solid salmon',765+ backgroundColor: '#fff',766+ cursor: 'pointer',767+ }}768+ onClick={() => setCurrentTabIndex(1)}769+ >770+ Tab 2771+ </button>772+ <button773+ type="button"774+ style={{775+ border: '1px solid salmon',776+ backgroundColor: '#fff',777+ cursor: 'pointer',778+ }}779+ onClick={() => setCurrentTabIndex(2)}780+ >781+ Tab 3782+ </button>783+ </div>784+ <div style={{ padding: 4 }}>785+ Content of Tab {currentTabIndex + 1}786+ <br /> <br />787+ <button type="button" onClick={() => counterState.increment()}>788+ Count: {counterState.count}789+ </button>790+ </div>791+ </div>792+ )793+}794+```795+796+Finally, we'll create the `App` component, which renders the tabs and their respective counters.797+The counter state is managed independently for each tab.798+799+```tsx800+export default function App() {801+ return (802+ <CounterStoresProvider>803+ <Tabs />804+ </CounterStoresProvider>805+ )806+}807+```808+809+Here is what the code should look like:810+811+```tsx812+import {813+ type ReactNode,814+ useState,815+ useCallback,816+ useContext,817+ createContext,818+} from 'react'819+import { createStore, useStore } from 'zustand'820+821+type CounterState = {822+ count: number823+}824+825+type CounterActions = { increment: () => void }826+827+type CounterStore = CounterState & CounterActions828+829+const createCounterStore = () => {830+ return createStore<CounterStore>()((set) => ({831+ count: 0,832+ increment: () => {833+ set((state) => ({ count: state.count + 1 }))834+ },835+ }))836+}837+838+const createCounterStoreFactory = (839+ counterStores: Map<string, ReturnType<typeof createCounterStore>>,840+) => {841+ return (counterStoreKey: string) => {842+ if (!counterStores.has(counterStoreKey)) {843+ counterStores.set(counterStoreKey, createCounterStore())844+ }845+ return counterStores.get(counterStoreKey)!846+ }847+}848+849+const CounterStoresContext = createContext<Map<850+ string,851+ ReturnType<typeof createCounterStore>852+> | null>(null)853+854+const CounterStoresProvider = ({ children }: { children: ReactNode }) => {855+ const [stores] = useState(856+ () => new Map<string, ReturnType<typeof createCounterStore>>(),857+ )858+859+ return (860+ <CounterStoresContext.Provider value={stores}>861+ {children}862+ </CounterStoresContext.Provider>863+ )864+}865+866+const useCounterStore = <U,>(867+ key: string,868+ selector: (state: CounterStore) => U,869+) => {870+ const stores = useContext(CounterStoresContext)871+872+ if (stores === undefined) {873+ throw new Error('useCounterStore must be used within CounterStoresProvider')874+ }875+876+ const getOrCreateCounterStoreByKey = useCallback(877+ (key: string) => createCounterStoreFactory(stores!)(key),878+ [stores],879+ )880+881+ return useStore(getOrCreateCounterStoreByKey(key), selector)882+}883+884+function Tabs() {885+ const [currentTabIndex, setCurrentTabIndex] = useState(0)886+ const counterState = useCounterStore(887+ `tab-${currentTabIndex}`,888+ (state) => state,889+ )890+891+ return (892+ <div style={{ fontFamily: 'monospace' }}>893+ <div894+ style={{895+ display: 'flex',896+ gap: '0.5rem',897+ borderBottom: '1px solid salmon',898+ paddingBottom: 4,899+ }}900+ >901+ <button902+ type="button"903+ style={{904+ border: '1px solid salmon',905+ backgroundColor: '#fff',906+ cursor: 'pointer',907+ }}908+ onClick={() => setCurrentTabIndex(0)}909+ >910+ Tab 1911+ </button>912+ <button913+ type="button"914+ style={{915+ border: '1px solid salmon',916+ backgroundColor: '#fff',917+ cursor: 'pointer',918+ }}919+ onClick={() => setCurrentTabIndex(1)}920+ >921+ Tab 2922+ </button>923+ <button924+ type="button"925+ style={{926+ border: '1px solid salmon',927+ backgroundColor: '#fff',928+ cursor: 'pointer',929+ }}930+ onClick={() => setCurrentTabIndex(2)}931+ >932+ Tab 3933+ </button>934+ </div>935+ <div style={{ padding: 4 }}>936+ Content of Tab {currentTabIndex + 1}937+ <br /> <br />938+ <button type="button" onClick={() => counterState.increment()}>939+ Count: {counterState.count}940+ </button>941+ </div>942+ </div>943+ )944+}945+946+export default function App() {947+ return (948+ <CounterStoresProvider>949+ <Tabs />950+ </CounterStoresProvider>951+ )952+}953+```954+955+## Troubleshooting956+957+TBDadded:docs/reference/hooks/use-store.md+923 added
1+---2+title: useStore3+description: How to use vanilla stores in React4+tag: react5+nav: 256+---7+8+`useStore` is a React Hook that lets you use a vanilla store in React.9+10+```js11+const someState = useStore(store, selectorFn)12+```13+14+- [Types](#types)15+ - [Signature](#signature)16+- [Reference](#reference)17+- [Usage](#usage)18+ - [Use a vanilla store in React](#use-a-vanilla-store-in-react)19+ - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)20+ - [Using scoped (non-global) vanilla store in React](#using-scoped-non-global-vanilla-store-in-react)21+ - [Using dynamic scoped (non-global) vanilla stores in React](#using-dynamic-scoped-non-global-vanilla-stores-in-react)22+- [Troubleshooting](#troubleshooting)23+24+## Types25+26+### Signature27+28+```ts29+useStore<StoreApi<T>, U = T>(store: StoreApi<T>, selectorFn?: (state: T) => U) => UseBoundStore<StoreApi<T>>30+```31+32+## Reference33+34+### `useStore(store, selectorFn)`35+36+#### Parameters37+38+- `storeApi`: The instance that lets you access to store API utilities.39+- `selectorFn`: A function that lets you return data that is based on current state.40+41+#### Returns42+43+`useStore` returns any data based on current state depending on the selector function. It should44+take a store, and a selector function as arguments.45+46+## Usage47+48+### Using a global vanilla store in React49+50+First, let's set up a store that will hold the position of the dot on the screen. We'll define the51+store to manage `x` and `y` coordinates and provide an action to update these coordinates.52+53+```tsx54+type PositionStoreState = { position: { x: number; y: number } }55+56+type PositionStoreActions = {57+ setPosition: (nextPosition: PositionStoreState['position']) => void58+}59+60+type PositionStore = PositionStoreState & PositionStoreActions61+62+const positionStore = createStore<PositionStore>()((set) => ({63+ position: { x: 0, y: 0 },64+ setPosition: (position) => set({ position }),65+}))66+```67+68+Next, we'll create a `MovingDot` component that renders a div representing the dot. This component69+will use the store to track and update the dot's position.70+71+```tsx72+function MovingDot() {73+ const position = useStore(positionStore, (state) => state.position)74+ const setPosition = useStore(positionStore, (state) => state.setPosition)75+76+ return (77+ <div78+ onPointerMove={(e) => {79+ setPosition({80+ x: e.clientX,81+ y: e.clientY,82+ })83+ }}84+ style={{85+ position: 'relative',86+ width: '100vw',87+ height: '100vh',88+ }}89+ >90+ <div91+ style={{92+ position: 'absolute',93+ backgroundColor: 'red',94+ borderRadius: '50%',95+ transform: `translate(${position.x}px, ${position.y}px)`,96+ left: -10,97+ top: -10,98+ width: 20,99+ height: 20,100+ }}101+ />102+ </div>103+ )104+}105+```106+107+Finally, we’ll render the `MovingDot` component in our `App` component.108+109+```tsx110+export default function App() {111+ return <MovingDot />112+}113+```114+115+Here is what the code should look like:116+117+```tsx118+import { createStore, useStore } from 'zustand'119+120+type PositionStoreState = { position: { x: number; y: number } }121+122+type PositionStoreActions = {123+ setPosition: (nextPosition: PositionStoreState['position']) => void124+}125+126+type PositionStore = PositionStoreState & PositionStoreActions127+128+const positionStore = createStore<PositionStore>()((set) => ({129+ position: { x: 0, y: 0 },130+ setPosition: (position) => set({ position }),131+}))132+133+function MovingDot() {134+ const position = useStore(positionStore, (state) => state.position)135+ const setPosition = useStore(positionStore, (state) => state.setPosition)136+137+ return (138+ <div139+ onPointerMove={(e) => {140+ setPosition({141+ x: e.clientX,142+ y: e.clientY,143+ })144+ }}145+ style={{146+ position: 'relative',147+ width: '100vw',148+ height: '100vh',149+ }}150+ >151+ <div152+ style={{153+ position: 'absolute',154+ backgroundColor: 'red',155+ borderRadius: '50%',156+ transform: `translate(${position.x}px, ${position.y}px)`,157+ left: -10,158+ top: -10,159+ width: 20,160+ height: 20,161+ }}162+ />163+ </div>164+ )165+}166+167+export default function App() {168+ return <MovingDot />169+}170+```171+172+### Using dynamic global vanilla stores in React173+174+First, we'll create a factory function that generates a store for managing the counter state.175+Each tab will have its own instance of this store.176+177+```ts178+type CounterState = {179+ count: number180+}181+182+type CounterActions = { increment: () => void }183+184+type CounterStore = CounterState & CounterActions185+186+const createCounterStore = () => {187+ return createStore<CounterStore>()((set) => ({188+ count: 0,189+ increment: () => {190+ set((state) => ({ count: state.count + 1 }))191+ },192+ }))193+}194+```195+196+Next, we'll create a factory function that manages the creation and retrieval of counter stores.197+This allows each tab to have its own independent counter.198+199+```ts200+const defaultCounterStores = new Map<201+ string,202+ ReturnType<typeof createCounterStore>203+>()204+205+const createCounterStoreFactory = (206+ counterStores: typeof defaultCounterStores,207+) => {208+ return (counterStoreKey: string) => {209+ if (!counterStores.has(counterStoreKey)) {210+ counterStores.set(counterStoreKey, createCounterStore())211+ }212+ return counterStores.get(counterStoreKey)!213+ }214+}215+216+const getOrCreateCounterStoreByKey =217+ createCounterStoreFactory(defaultCounterStores)218+```219+220+Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s221+counter.222+223+```tsx224+const [currentTabIndex, setCurrentTabIndex] = useState(0)225+const counterState = useStore(226+ getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),227+)228+229+return (230+ <div style={{ fontFamily: 'monospace' }}>231+ <div232+ style={{233+ display: 'flex',234+ gap: '0.5rem',235+ borderBottom: '1px solid salmon',236+ paddingBottom: 4,237+ }}238+ >239+ <button240+ type="button"241+ style={{242+ border: '1px solid salmon',243+ backgroundColor: '#fff',244+ cursor: 'pointer',245+ }}246+ onClick={() => setCurrentTabIndex(0)}247+ >248+ Tab 1249+ </button>250+ <button251+ type="button"252+ style={{253+ border: '1px solid salmon',254+ backgroundColor: '#fff',255+ cursor: 'pointer',256+ }}257+ onClick={() => setCurrentTabIndex(1)}258+ >259+ Tab 2260+ </button>261+ <button262+ type="button"263+ style={{264+ border: '1px solid salmon',265+ backgroundColor: '#fff',266+ cursor: 'pointer',267+ }}268+ onClick={() => setCurrentTabIndex(2)}269+ >270+ Tab 3271+ </button>272+ </div>273+ <div style={{ padding: 4 }}>274+ Content of Tab {currentTabIndex + 1}275+ <br /> <br />276+ <button type="button" onClick={() => counterState.increment()}>277+ Count: {counterState.count}278+ </button>279+ </div>280+ </div>281+)282+```283+284+Finally, we'll create the `App` component, which renders the tabs and their respective counters.285+The counter state is managed independently for each tab.286+287+```tsx288+export default function App() {289+ return <Tabs />290+}291+```292+293+Here is what the code should look like:294+295+```tsx296+import { useState } from 'react'297+import { createStore, useStore } from 'zustand'298+299+type CounterState = {300+ count: number301+}302+303+type CounterActions = { increment: () => void }304+305+type CounterStore = CounterState & CounterActions306+307+const createCounterStore = () => {308+ return createStore<CounterStore>()((set) => ({309+ count: 0,310+ increment: () => {311+ set((state) => ({ count: state.count + 1 }))312+ },313+ }))314+}315+316+const defaultCounterStores = new Map<317+ string,318+ ReturnType<typeof createCounterStore>319+>()320+321+const createCounterStoreFactory = (322+ counterStores: typeof defaultCounterStores,323+) => {324+ return (counterStoreKey: string) => {325+ if (!counterStores.has(counterStoreKey)) {326+ counterStores.set(counterStoreKey, createCounterStore())327+ }328+ return counterStores.get(counterStoreKey)!329+ }330+}331+332+const getOrCreateCounterStoreByKey =333+ createCounterStoreFactory(defaultCounterStores)334+335+export default function App() {336+ const [currentTabIndex, setCurrentTabIndex] = useState(0)337+ const counterState = useStore(338+ getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),339+ )340+341+ return (342+ <div style={{ fontFamily: 'monospace' }}>343+ <div344+ style={{345+ display: 'flex',346+ gap: '0.5rem',347+ borderBottom: '1px solid salmon',348+ paddingBottom: 4,349+ }}350+ >351+ <button352+ type="button"353+ style={{354+ border: '1px solid salmon',355+ backgroundColor: '#fff',356+ cursor: 'pointer',357+ }}358+ onClick={() => setCurrentTabIndex(0)}359+ >360+ Tab 1361+ </button>362+ <button363+ type="button"364+ style={{365+ border: '1px solid salmon',366+ backgroundColor: '#fff',367+ cursor: 'pointer',368+ }}369+ onClick={() => setCurrentTabIndex(1)}370+ >371+ Tab 2372+ </button>373+ <button374+ type="button"375+ style={{376+ border: '1px solid salmon',377+ backgroundColor: '#fff',378+ cursor: 'pointer',379+ }}380+ onClick={() => setCurrentTabIndex(2)}381+ >382+ Tab 3383+ </button>384+ </div>385+ <div style={{ padding: 4 }}>386+ Content of Tab {currentTabIndex + 1}387+ <br /> <br />388+ <button type="button" onClick={() => counterState.increment()}>389+ Count: {counterState.count}390+ </button>391+ </div>392+ </div>393+ )394+}395+```396+397+### Using scoped (non-global) vanilla store in React398+399+First, let's set up a store that will hold the position of the dot on the screen. We'll define the400+store to manage `x` and `y` coordinates and provide an action to update these coordinates.401+402+```tsx403+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 createPositionStore = () => {412+ return createStore<PositionStore>()((set) => ({413+ position: { x: 0, y: 0 },414+ setPosition: (position) => set({ position }),415+ }))416+}417+```418+419+Next, we'll create a context and a provider component to pass down the store through the React420+component tree. This allows each `MovingDot` component to have its own independent state.421+422+```tsx423+const PositionStoreContext = createContext<ReturnType<424+ typeof createPositionStore425+> | null>(null)426+427+function PositionStoreProvider({ children }: { children: ReactNode }) {428+ const [store] = useState(() => createPositionStore())429+ return (430+ <PositionStoreContext.Provider value={store}>431+ {children}432+ </PositionStoreContext.Provider>433+ )434+}435+```436+437+To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook438+will read the store from the context and allow us to select specific parts of the state.439+440+```ts441+function usePositionStore<U>(selector: (state: PositionStore) => U) {442+ const store = useContext(PositionStoreContext)443+444+ if (store === null) {445+ throw new Error(446+ 'usePositionStore must be used within PositionStoreProvider',447+ )448+ }449+450+ return useStore(store, selector)451+}452+```453+454+Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor455+within its container.456+457+```tsx458+function MovingDot({ color }: { color: string }) {459+ const position = usePositionStore((state) => state.position)460+ const setPosition = usePositionStore((state) => state.setPosition)461+462+ return (463+ <div464+ onPointerMove={(e) => {465+ setPosition({466+ x:467+ e.clientX > e.currentTarget.clientWidth468+ ? e.clientX - e.currentTarget.clientWidth469+ : e.clientX,470+ y: e.clientY,471+ })472+ }}473+ style={{474+ position: 'relative',475+ width: '50vw',476+ height: '100vh',477+ }}478+ >479+ <div480+ style={{481+ position: 'absolute',482+ backgroundColor: color,483+ borderRadius: '50%',484+ transform: `translate(${position.x}px, ${position.y}px)`,485+ left: -10,486+ top: -10,487+ width: 20,488+ height: 20,489+ }}490+ />491+ </div>492+ )493+}494+```495+496+Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`497+components, each with its own independent state.498+499+```tsx500+export default function App() {501+ return (502+ <div style={{ display: 'flex' }}>503+ <PositionStoreProvider>504+ <MovingDot color="red" />505+ </PositionStoreProvider>506+ <PositionStoreProvider>507+ <MovingDot color="blue" />508+ </PositionStoreProvider>509+ </div>510+ )511+}512+```513+514+Here is what the code should look like:515+516+```tsx517+import { type ReactNode, useState, createContext, useContext } from 'react'518+import { createStore, useStore } from 'zustand'519+520+type PositionStoreState = { position: { x: number; y: number } }521+522+type PositionStoreActions = {523+ setPosition: (nextPosition: PositionStoreState['position']) => void524+}525+526+type PositionStore = PositionStoreState & PositionStoreActions527+528+const createPositionStore = () => {529+ return createStore<PositionStore>()((set) => ({530+ position: { x: 0, y: 0 },531+ setPosition: (position) => set({ position }),532+ }))533+}534+535+const PositionStoreContext = createContext<ReturnType<536+ typeof createPositionStore537+> | null>(null)538+539+function PositionStoreProvider({ children }: { children: ReactNode }) {540+ const [store] = useState(() => createPositionStore())541+ return (542+ <PositionStoreContext.Provider value={store}>543+ {children}544+ </PositionStoreContext.Provider>545+ )546+}547+548+function usePositionStore<U>(selector: (state: PositionStore) => U) {549+ const store = useContext(PositionStoreContext)550+551+ if (store === null) {552+ throw new Error(553+ 'usePositionStore must be used within PositionStoreProvider',554+ )555+ }556+557+ return useStore(store, selector)558+}559+560+function MovingDot({ color }: { color: string }) {561+ const position = usePositionStore((state) => state.position)562+ const setPosition = usePositionStore((state) => state.setPosition)563+564+ return (565+ <div566+ onPointerMove={(e) => {567+ setPosition({568+ x:569+ e.clientX > e.currentTarget.clientWidth570+ ? e.clientX - e.currentTarget.clientWidth571+ : e.clientX,572+ y: e.clientY,573+ })574+ }}575+ style={{576+ position: 'relative',577+ width: '50vw',578+ height: '100vh',579+ }}580+ >581+ <div582+ style={{583+ position: 'absolute',584+ backgroundColor: color,585+ borderRadius: '50%',586+ transform: `translate(${position.x}px, ${position.y}px)`,587+ left: -10,588+ top: -10,589+ width: 20,590+ height: 20,591+ }}592+ />593+ </div>594+ )595+}596+597+export default function App() {598+ return (599+ <div style={{ display: 'flex' }}>600+ <PositionStoreProvider>601+ <MovingDot color="red" />602+ </PositionStoreProvider>603+ <PositionStoreProvider>604+ <MovingDot color="blue" />605+ </PositionStoreProvider>606+ </div>607+ )608+}609+```610+611+### Using dynamic scoped (non-global) vanilla stores in React612+613+First, we'll create a factory function that generates a store for managing the counter state.614+Each tab will have its own instance of this store.615+616+```ts617+import { createStore } from 'zustand'618+619+type CounterState = {620+ count: number621+}622+623+type CounterActions = { increment: () => void }624+625+type CounterStore = CounterState & CounterActions626+627+const createCounterStore = () => {628+ return createStore<CounterStore>()((set) => ({629+ count: 0,630+ increment: () => {631+ set((state) => ({ count: state.count + 1 }))632+ },633+ }))634+}635+```636+637+Next, we'll create a factory function that manages the creation and retrieval of counter stores.638+This allows each tab to have its own independent counter.639+640+```ts641+const createCounterStoreFactory = (642+ counterStores: Map<string, ReturnType<typeof createCounterStore>>,643+) => {644+ return (counterStoreKey: string) => {645+ if (!counterStores.has(counterStoreKey)) {646+ counterStores.set(counterStoreKey, createCounterStore())647+ }648+ return counterStores.get(counterStoreKey)!649+ }650+}651+```652+653+Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context654+for this.655+656+```tsx657+const CounterStoresContext = createContext(null)658+659+const CounterStoresProvider = ({ children }) => {660+ const [stores] = useState(661+ () => new Map<string, ReturnType<typeof createCounterStore>>(),662+ )663+664+ return (665+ <CounterStoresContext.Provider value={stores}>666+ {children}667+ </CounterStoresContext.Provider>668+ )669+}670+```671+672+Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a673+given tab.674+675+```tsx676+const useCounterStore = <U>(677+ currentTabIndex: number,678+ selector: (state: CounterStore) => U,679+) => {680+ const stores = useContext(CounterStoresContext)681+682+ if (stores === undefined) {683+ throw new Error('useCounterStore must be used within CounterStoresProvider')684+ }685+686+ const getOrCreateCounterStoreByKey = useCallback(687+ () => createCounterStoreFactory(stores),688+ [stores],689+ )690+691+ return useStore(getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`))692+}693+```694+695+Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s696+counter.697+698+```tsx699+function Tabs() {700+ const [currentTabIndex, setCurrentTabIndex] = useState(0)701+ const counterState = useCounterStore(702+ `tab-${currentTabIndex}`,703+ (state) => state,704+ )705+706+ return (707+ <div style={{ fontFamily: 'monospace' }}>708+ <div709+ style={{710+ display: 'flex',711+ gap: '0.5rem',712+ borderBottom: '1px solid salmon',713+ paddingBottom: 4,714+ }}715+ >716+ <button717+ type="button"718+ style={{719+ border: '1px solid salmon',720+ backgroundColor: '#fff',721+ cursor: 'pointer',722+ }}723+ onClick={() => setCurrentTabIndex(0)}724+ >725+ Tab 1726+ </button>727+ <button728+ type="button"729+ style={{730+ border: '1px solid salmon',731+ backgroundColor: '#fff',732+ cursor: 'pointer',733+ }}734+ onClick={() => setCurrentTabIndex(1)}735+ >736+ Tab 2737+ </button>738+ <button739+ type="button"740+ style={{741+ border: '1px solid salmon',742+ backgroundColor: '#fff',743+ cursor: 'pointer',744+ }}745+ onClick={() => setCurrentTabIndex(2)}746+ >747+ Tab 3748+ </button>749+ </div>750+ <div style={{ padding: 4 }}>751+ Content of Tab {currentTabIndex + 1}752+ <br /> <br />753+ <button type="button" onClick={() => counterState.increment()}>754+ Count: {counterState.count}755+ </button>756+ </div>757+ </div>758+ )759+}760+```761+762+Finally, we'll create the `App` component, which renders the tabs and their respective counters.763+The counter state is managed independently for each tab.764+765+```tsx766+export default function App() {767+ return (768+ <CounterStoresProvider>769+ <Tabs />770+ </CounterStoresProvider>771+ )772+}773+```774+775+Here is what the code should look like:776+777+```tsx778+import {779+ type ReactNode,780+ useState,781+ useCallback,782+ useContext,783+ createContext,784+} from 'react'785+import { createStore, useStore } from 'zustand'786+787+type CounterState = {788+ count: number789+}790+791+type CounterActions = { increment: () => void }792+793+type CounterStore = CounterState & CounterActions794+795+const createCounterStore = () => {796+ return createStore<CounterStore>()((set) => ({797+ count: 0,798+ increment: () => {799+ set((state) => ({ count: state.count + 1 }))800+ },801+ }))802+}803+804+const createCounterStoreFactory = (805+ counterStores: Map<string, ReturnType<typeof createCounterStore>>,806+) => {807+ return (counterStoreKey: string) => {808+ if (!counterStores.has(counterStoreKey)) {809+ counterStores.set(counterStoreKey, createCounterStore())810+ }811+ return counterStores.get(counterStoreKey)!812+ }813+}814+815+const CounterStoresContext = createContext<Map<816+ string,817+ ReturnType<typeof createCounterStore>818+> | null>(null)819+820+const CounterStoresProvider = ({ children }: { children: ReactNode }) => {821+ const [stores] = useState(822+ () => new Map<string, ReturnType<typeof createCounterStore>>(),823+ )824+825+ return (826+ <CounterStoresContext.Provider value={stores}>827+ {children}828+ </CounterStoresContext.Provider>829+ )830+}831+832+const useCounterStore = <U,>(833+ key: string,834+ selector: (state: CounterStore) => U,835+) => {836+ const stores = useContext(CounterStoresContext)837+838+ if (stores === undefined) {839+ throw new Error('useCounterStore must be used within CounterStoresProvider')840+ }841+842+ const getOrCreateCounterStoreByKey = useCallback(843+ (key: string) => createCounterStoreFactory(stores!)(key),844+ [stores],845+ )846+847+ return useStore(getOrCreateCounterStoreByKey(key), selector)848+}849+850+function Tabs() {851+ const [currentTabIndex, setCurrentTabIndex] = useState(0)852+ const counterState = useCounterStore(853+ `tab-${currentTabIndex}`,854+ (state) => state,855+ )856+857+ return (858+ <div style={{ fontFamily: 'monospace' }}>859+ <div860+ style={{861+ display: 'flex',862+ gap: '0.5rem',863+ borderBottom: '1px solid salmon',864+ paddingBottom: 4,865+ }}866+ >867+ <button868+ type="button"869+ style={{870+ border: '1px solid salmon',871+ backgroundColor: '#fff',872+ cursor: 'pointer',873+ }}874+ onClick={() => setCurrentTabIndex(0)}875+ >876+ Tab 1877+ </button>878+ <button879+ type="button"880+ style={{881+ border: '1px solid salmon',882+ backgroundColor: '#fff',883+ cursor: 'pointer',884+ }}885+ onClick={() => setCurrentTabIndex(1)}886+ >887+ Tab 2888+ </button>889+ <button890+ type="button"891+ style={{892+ border: '1px solid salmon',893+ backgroundColor: '#fff',894+ cursor: 'pointer',895+ }}896+ onClick={() => setCurrentTabIndex(2)}897+ >898+ Tab 3899+ </button>900+ </div>901+ <div style={{ padding: 4 }}>902+ Content of Tab {currentTabIndex + 1}903+ <br /> <br />904+ <button type="button" onClick={() => counterState.increment()}>905+ Count: {counterState.count}906+ </button>907+ </div>908+ </div>909+ )910+}911+912+export default function App() {913+ return (914+ <CounterStoresProvider>915+ <Tabs />916+ </CounterStoresProvider>917+ )918+}919+```920+921+## Troubleshooting922+923+TBDadded:docs/reference/integrations/immer-middleware.md+129 added
1+---2+title: Immer middleware3+nav: 354+---5+6+The [Immer](https://github.com/immerjs/immer) middleware enables you7+to use immutable state in a more convenient way.8+Also, with Immer, you can simplify handling9+immutable data structures in Zustand.10+11+## Installation12+13+In order to use the Immer middleware in Zustand,14+you will need to install Immer as a direct dependency.15+16+```bash17+npm install immer18+```19+20+## Usage21+22+(Notice the extra parentheses after the type parameter as mentioned in the [Advanced Typescript Guide](../../learn/guides/advanced-typescript.md)).23+24+Updating simple states25+26+```ts27+import { create } from 'zustand'28+import { immer } from 'zustand/middleware/immer'29+30+type State = {31+ count: number32+}33+34+type Actions = {35+ increment: (qty: number) => void36+ decrement: (qty: number) => void37+}38+39+export const useCountStore = create<State & Actions>()(40+ immer((set) => ({41+ count: 0,42+ increment: (qty: number) =>43+ set((state) => {44+ state.count += qty45+ }),46+ decrement: (qty: number) =>47+ set((state) => {48+ state.count -= qty49+ }),50+ })),51+)52+```53+54+Updating complex states55+56+```ts57+import { create } from 'zustand'58+import { immer } from 'zustand/middleware/immer'59+60+interface Todo {61+ id: string62+ title: string63+ done: boolean64+}65+66+type State = {67+ todos: Record<string, Todo>68+}69+70+type Actions = {71+ toggleTodo: (todoId: string) => void72+}73+74+export const useTodoStore = create<State & Actions>()(75+ immer((set) => ({76+ todos: {77+ '82471c5f-4207-4b1d-abcb-b98547e01a3e': {78+ id: '82471c5f-4207-4b1d-abcb-b98547e01a3e',79+ title: 'Learn Zustand',80+ done: false,81+ },82+ '354ee16c-bfdd-44d3-afa9-e93679bda367': {83+ id: '354ee16c-bfdd-44d3-afa9-e93679bda367',84+ title: 'Learn Jotai',85+ done: false,86+ },87+ '771c85c5-46ea-4a11-8fed-36cc2c7be344': {88+ id: '771c85c5-46ea-4a11-8fed-36cc2c7be344',89+ title: 'Learn Valtio',90+ done: false,91+ },92+ '363a4bac-083f-47f7-a0a2-aeeee153a99c': {93+ id: '363a4bac-083f-47f7-a0a2-aeeee153a99c',94+ title: 'Learn Signals',95+ done: false,96+ },97+ },98+ toggleTodo: (todoId: string) =>99+ set((state) => {100+ state.todos[todoId].done = !state.todos[todoId].done101+ }),102+ })),103+)104+```105+106+## Gotchas107+108+In this section you will find some things109+that you need to keep in mind when using Zustand with Immer.110+111+### My subscriptions aren't being called112+113+If you are using Immer,114+make sure you are actually following115+[the rules of Immer](https://immerjs.github.io/immer/pitfalls).116+117+For example, you have to add `[immerable] = true` for118+[class objects](https://immerjs.github.io/immer/complex-objects) to work.119+If you don't do this, Immer will still mutate the object,120+but not as a proxy, so it will also update the current state.121+Zustand checks if the state has actually changed,122+so since both the current state and the next state are123+equal (if you don't do it correctly),124+Zustand will skip calling the subscriptions.125+126+## Demos127+128+- Basic: https://stackblitz.com/edit/vitejs-vite-3sgc4ejy129+- Advanced: https://stackblitz.com/edit/vitejs-vite-jxxtuyj3added:docs/reference/integrations/persisting-store-data.md+834 added
1+---2+title: Persisting store data3+nav: 344+---5+6+The Persist middleware enables you to store7+your Zustand state in a storage8+(e.g., `localStorage`, `AsyncStorage`, `IndexedDB`, etc.),9+thus persisting its data.10+11+Note that this middleware supports both12+synchronous storages, like `localStorage`,13+and asynchronous storages, like `AsyncStorage`,14+but using an asynchronous storage does come with a cost.15+See [Hydration and asynchronous storages](#hydration-and-asynchronous-storages)16+for more details.17+18+## Simple example19+20+```ts21+import { create } from 'zustand'22+import { persist, createJSONStorage } from 'zustand/middleware'23+24+export const useBearStore = create()(25+ persist(26+ (set, get) => ({27+ bears: 0,28+ addABear: () => set({ bears: get().bears + 1 }),29+ }),30+ {31+ name: 'food-storage', // name of the item in the storage (must be unique)32+ storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used33+ },34+ ),35+)36+```37+38+## Typescript simple example39+40+```ts41+import { create } from 'zustand'42+import { persist, createJSONStorage } from 'zustand/middleware'43+44+type BearStore = {45+ bears: number46+ addABear: () => void47+}48+49+export const useBearStore = create<BearStore>()(50+ persist(51+ (set, get) => ({52+ bears: 0,53+ addABear: () => set({ bears: get().bears + 1 }),54+ }),55+ {56+ name: 'food-storage', // name of the item in the storage (must be unique)57+ storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used58+ },59+ ),60+)61+```62+63+## Options64+65+### `name`66+67+This is the only required option.68+The given name is going to be the key69+used to store your Zustand state in the storage,70+so it must be unique.71+72+### `storage`73+74+> Type: `() => StateStorage`75+76+The `StateStorage` can be imported with:77+78+```ts79+import { StateStorage } from 'zustand/middleware'80+```81+82+> Default: `createJSONStorage(() => localStorage)`83+84+Enables you to use your own storage. Simply pass a function that returns the storage you want to use. It's recommended to use the [`createJSONStorage`](#createjsonstorage) helper function to create a `storage` object that is compliant with the `StateStorage` interface.85+86+Example:87+88+```ts89+import { persist, createJSONStorage } from 'zustand/middleware'90+91+export const useBoundStore = create(92+ persist(93+ (set, get) => ({94+ // ...95+ }),96+ {97+ // ...98+ storage: createJSONStorage(() => AsyncStorage),99+ },100+ ),101+)102+```103+104+### `partialize`105+106+> Type: `(state: Object) => Object`107+108+> Default: `(state) => state`109+110+Enables you to pick some of the state's fields to be stored in the storage.111+112+You could omit multiple fields using the following:113+114+```ts115+export const useBoundStore = create(116+ persist(117+ (set, get) => ({118+ foo: 0,119+ bar: 1,120+ }),121+ {122+ // ...123+ partialize: (state) =>124+ Object.fromEntries(125+ Object.entries(state).filter(([key]) => !['foo'].includes(key)),126+ ),127+ },128+ ),129+)130+```131+132+Or you could allow only specific fields using the following:133+134+```ts135+export const useBoundStore = create(136+ persist(137+ (set, get) => ({138+ foo: 0,139+ bar: 1,140+ }),141+ {142+ // ...143+ partialize: (state) => ({ foo: state.foo }),144+ },145+ ),146+)147+```148+149+### `onRehydrateStorage`150+151+> Type: `(state: Object) => ((state?: Object, error?: Error) => void) | void`152+153+This option enables you to pass a listener function154+that will be called when the storage is hydrated.155+156+Example:157+158+```ts159+export const useBoundStore = create(160+ persist(161+ (set, get) => ({162+ // ...163+ }),164+ {165+ // ...166+ onRehydrateStorage: (state) => {167+ console.log('hydration starts')168+169+ // optional170+ return (state, error) => {171+ if (error) {172+ console.log('an error happened during hydration', error)173+ } else {174+ console.log('hydration finished')175+ }176+ }177+ },178+ },179+ ),180+)181+```182+183+### `version`184+185+> Type: `number`186+187+> Default: `0`188+189+If you want to introduce a breaking change in your storage190+(e.g. renaming a field), you can specify a new version number.191+By default, if the version in the storage192+does not match the version in the code,193+the stored value won't be used.194+You can use the [migrate](#migrate) function (see below)195+to handle breaking changes in order to persist previously stored data.196+197+### `migrate`198+199+> Type: `(persistedState: Object, version: number) => Object | Promise<Object>`200+201+> Default: `(persistedState) => persistedState`202+203+You can use this option to handle versions migration.204+The migrate function takes the persisted state205+and the version number as arguments.206+It must return a state that is compliant207+to the latest version (the version in the code).208+209+For instance, if you want to rename a field, you can use the following:210+211+```ts212+export const useBoundStore = create(213+ persist(214+ (set, get) => ({215+ newField: 0, // let's say this field was named otherwise in version 0216+ }),217+ {218+ // ...219+ version: 1, // a migration will be triggered if the version in the storage mismatches this one220+ migrate: (persistedState, version) => {221+ if (version === 0) {222+ // if the stored value is in version 0, we rename the field to the new name223+ persistedState.newField = persistedState.oldField224+ delete persistedState.oldField225+ }226+227+ return persistedState228+ },229+ },230+ ),231+)232+```233+234+### `merge`235+236+> Type: `(persistedState: Object, currentState: Object) => Object`237+238+> Default: `(persistedState, currentState) => ({ ...currentState, ...persistedState })`239+240+In some cases, you might want to use a custom merge function241+to merge the persisted value with the current state.242+243+By default, the middleware does a shallow merge.244+The shallow merge might not be enough245+if you have partially persisted nested objects.246+For instance, if the storage contains the following:247+248+```ts249+{250+ foo: {251+ bar: 0,252+ }253+}254+```255+256+But your Zustand store contains:257+258+```ts259+{260+ foo: {261+ bar: 0,262+ baz: 1,263+ }264+}265+```266+267+The shallow merge will erase the `baz` field from the `foo` object.268+One way to fix this would be to give a custom deep merge function:269+270+```ts271+export const useBoundStore = create(272+ persist(273+ (set, get) => ({274+ foo: {275+ bar: 0,276+ baz: 1,277+ },278+ }),279+ {280+ // ...281+ merge: (persistedState, currentState) =>282+ deepMerge(currentState, persistedState),283+ },284+ ),285+)286+```287+288+### `skipHydration`289+290+> Type: `boolean | undefined`291+292+> Default: `undefined`293+294+By default the store will be hydrated on initialization.295+296+In some applications you may need to control when the first hydration occurs.297+For example, in server-rendered apps.298+299+If you set `skipHydration`, the initial call for hydration isn't called,300+and it is left up to you to manually call `rehydrate()`.301+302+```ts303+export const useBoundStore = create(304+ persist(305+ () => ({306+ count: 0,307+ // ...308+ }),309+ {310+ // ...311+ skipHydration: true,312+ },313+ ),314+)315+```316+317+```tsx318+import { useBoundStore } from './path-to-store';319+320+export function StoreConsumer() {321+ // hydrate persisted store after on mount322+ useEffect(() => {323+ useBoundStore.persist.rehydrate();324+ }, [])325+326+ return (327+ //...328+ )329+}330+```331+332+## API333+334+> Version: >=3.6.3335+336+The Persist API enables you to do a number of interactions337+with the Persist middleware338+from inside or outside of a React component.339+340+### `getOptions`341+342+> Type: `() => Partial<PersistOptions>`343+344+> Returns: Options of the Persist middleware345+346+For example, it can be used to obtain the storage name:347+348+```ts349+useBoundStore.persist.getOptions().name350+```351+352+### `setOptions`353+354+> Type: `(newOptions: Partial<PersistOptions>) => void`355+356+Changes the middleware options.357+Note that the new options will be merged with the current ones.358+359+For instance, this can be used to change the storage name:360+361+```ts362+useBoundStore.persist.setOptions({363+ name: 'new-name',364+})365+```366+367+Or even to change the storage engine:368+369+```ts370+useBoundStore.persist.setOptions({371+ storage: createJSONStorage(() => sessionStorage),372+})373+```374+375+### `clearStorage`376+377+> Type: `() => void`378+379+Clears everything stored under the [name](#name) key.380+381+```ts382+useBoundStore.persist.clearStorage()383+```384+385+### `rehydrate`386+387+> Type: `() => Promise<void>`388+389+In some cases, you might want to trigger the rehydration manually.390+This can be done by calling the `rehydrate` method.391+392+```ts393+await useBoundStore.persist.rehydrate()394+```395+396+### `hasHydrated`397+398+> Type: `() => boolean`399+400+This is a non-reactive getter to check401+if the storage has been hydrated402+(note that it updates when calling [`rehydrate`](#rehydrate)).403+404+```ts405+useBoundStore.persist.hasHydrated()406+```407+408+### `onHydrate`409+410+> Type: `(listener: (state) => void) => () => void`411+412+> Returns: Unsubscribe function413+414+This listener will be called when the hydration process starts.415+416+```ts417+const unsub = useBoundStore.persist.onHydrate((state) => {418+ console.log('hydration starts')419+})420+421+// later on...422+unsub()423+```424+425+### `onFinishHydration`426+427+> Type: `(listener: (state) => void) => () => void`428+429+> Returns: Unsubscribe function430+431+This listener will be called when the hydration process ends.432+433+```ts434+const unsub = useBoundStore.persist.onFinishHydration((state) => {435+ console.log('hydration finished')436+})437+438+// later on...439+unsub()440+```441+442+### `createJSONStorage`443+444+> Type: `(getStorage: () => StateStorage, options?: JsonStorageOptions) => StateStorage`445+446+> Returns: `PersistStorage`447+448+This helper function enables you to create a [`storage`](#storage) object which is useful when you want to use a custom storage engine.449+450+`getStorage` is a function that returns the storage engine with the properties `getItem`, `setItem`, and `removeItem`.451+452+`options` is an optional object that can be used to customize the serialization and deserialization of the data. `options.reviver` is a function that is passed to `JSON.parse` to deserialize the data. `options.replacer` is a function that is passed to `JSON.stringify` to serialize the data.453+454+```ts455+import { createJSONStorage } from 'zustand/middleware'456+457+const storage = createJSONStorage(() => sessionStorage, {458+ reviver: (key, value) => {459+ if (value && value.type === 'date') {460+ return new Date(value)461+ }462+ return value463+ },464+ replacer: (key, value) => {465+ // NOTE: the result of `.toJSON()` is passed to the466+ // replacer function as value if is available so467+ // a Date is always a `string` at this point468+ if (key === 'someDate') return { type: 'date', value }469+ return value470+ },471+})472+```473+474+## Hydration and asynchronous storages475+476+To explain what is the "cost" of asynchronous storages,477+you need to understand what is hydration.478+479+In a nutshell, hydration is a process480+of retrieving persisted state from the storage481+and merging it with the current state.482+483+The Persist middleware does two kinds of hydration:484+synchronous and asynchronous.485+If the given storage is synchronous (e.g., `localStorage`),486+hydration will be done synchronously.487+On the other hand, if the given storage is asynchronous (e.g., `AsyncStorage`),488+hydration will be done asynchronously (shocking, I know!).489+490+But what's the catch?491+With synchronous hydration,492+the Zustand store will already have been hydrated at its creation.493+In contrast, with asynchronous hydration,494+the Zustand store will be hydrated later on, in a microtask.495+496+Why does it matter?497+Asynchronous hydration can cause some unexpected behaviors.498+For instance, if you use Zustand in a React app,499+the store will **not** be hydrated at the initial render.500+In cases where your app depends on the persisted value at page load,501+you might want to wait until502+the store has been hydrated before showing anything.503+For example, your app might think the user504+is not logged in because it's the default,505+but in reality the store has not been hydrated yet.506+507+If your app does depends on the persisted state at page load,508+see [_How can I check if my store has been hydrated_](#how-can-i-check-if-my-store-has-been-hydrated)509+in the [FAQ](#faq) section below.510+511+### Usage in Next.js512+513+NextJS uses Server Side Rendering, and it will compare the rendered component on the server with the one rendered on client.514+But since you are using data from browser to change your component, the two renders will differ and Next will throw a warning at you.515+516+The errors usually are:517+518+- Text content does not match server-rendered HTML519+- Hydration failed because the initial UI does not match what was rendered on the server520+- There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering521+522+To solve these errors, create a custom hook so that Zustand waits a little before changing your components.523+524+Create a file with the following:525+526+```ts527+// useStore.ts528+import { useState, useEffect } from 'react'529+530+const useStore = <T, F>(531+ store: (callback: (state: T) => unknown) => unknown,532+ callback: (state: T) => F,533+) => {534+ const result = store(callback) as F535+ const [data, setData] = useState<F>()536+537+ useEffect(() => {538+ setData(result)539+ }, [result])540+541+ return data542+}543+544+export default useStore545+```546+547+Now in your pages, you will use the hook a little bit differently:548+549+```ts550+// useBearStore.ts551+552+import { create } from 'zustand'553+import { persist } from 'zustand/middleware'554+555+// the store itself does not need any change556+export const useBearStore = create(557+ persist(558+ (set, get) => ({559+ bears: 0,560+ addABear: () => set({ bears: get().bears + 1 }),561+ }),562+ {563+ name: 'food-storage',564+ },565+ ),566+)567+```568+569+```ts570+// yourComponent.tsx571+572+import useStore from './useStore'573+import { useBearStore } from './stores/useBearStore'574+575+const bears = useStore(useBearStore, (state) => state.bears)576+```577+578+Credits: [This reply to an issue](https://github.com/pmndrs/zustand/issues/938#issuecomment-1481801942), which points to [this blog post](https://dev.to/abdulsamad/how-to-use-zustands-persist-middleware-in-nextjs-4lb5).579+580+## FAQ581+582+### How can I check if my store has been hydrated583+584+There are a few different ways to do this.585+586+You can use the [`onRehydrateStorage`](#onrehydratestorage)587+listener function to update a field in the store:588+589+```ts590+const useBoundStore = create(591+ persist(592+ (set, get) => ({593+ // ...594+ _hasHydrated: false,595+ setHasHydrated: (state) => {596+ set({597+ _hasHydrated: state598+ });599+ }600+ }),601+ {602+ // ...603+ onRehydrateStorage: (state) => {604+ return () => state.setHasHydrated(true)605+ }606+ }607+ )608+);609+610+export default function App() {611+ const hasHydrated = useBoundStore(state => state._hasHydrated);612+613+ if (!hasHydrated) {614+ return <p>Loading...</p>615+ }616+617+ return (618+ // ...619+ );620+}621+```622+623+You can also create a custom `useHydration` hook:624+625+```ts626+const useBoundStore = create(persist(...))627+628+const useHydration = () => {629+ const [hydrated, setHydrated] = useState(false)630+631+ useEffect(() => {632+ // Note: This is just in case you want to take into account manual rehydration.633+ // You can remove the following line if you don't need it.634+ const unsubHydrate = useBoundStore.persist.onHydrate(() => setHydrated(false))635+636+ const unsubFinishHydration = useBoundStore.persist.onFinishHydration(() => setHydrated(true))637+638+ setHydrated(useBoundStore.persist.hasHydrated())639+640+ return () => {641+ unsubHydrate()642+ unsubFinishHydration()643+ }644+ }, [])645+646+ return hydrated647+}648+```649+650+### How can I use a custom storage engine651+652+If the storage you want to use does not match the expected API, you can create your own storage:653+654+```ts655+import { create } from 'zustand'656+import { persist, createJSONStorage, StateStorage } from 'zustand/middleware'657+import { get, set, del } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.658+659+// Custom storage object660+const storage: StateStorage = {661+ getItem: async (name: string): Promise<string | null> => {662+ console.log(name, 'has been retrieved')663+ return (await get(name)) || null664+ },665+ setItem: async (name: string, value: string): Promise<void> => {666+ console.log(name, 'with value', value, 'has been saved')667+ await set(name, value)668+ },669+ removeItem: async (name: string): Promise<void> => {670+ console.log(name, 'has been deleted')671+ await del(name)672+ },673+}674+675+export const useBoundStore = create(676+ persist(677+ (set, get) => ({678+ bears: 0,679+ addABear: () => set({ bears: get().bears + 1 }),680+ }),681+ {682+ name: 'food-storage', // unique name683+ storage: createJSONStorage(() => storage),684+ },685+ ),686+)687+```688+689+If you're using a type that `JSON.stringify()` doesn't support, you'll need to write your own serialization/deserialization code. However, if this is tedious, you can use third-party libraries to serialize and deserialize different types of data.690+691+For example, [Superjson](https://github.com/blitz-js/superjson) can serialize data along with its type, allowing the data to be parsed back to its original type upon deserialization692+693+```ts694+import superjson from 'superjson' // can use anything: serialize-javascript, devalue, etc.695+import { PersistStorage } from 'zustand/middleware'696+697+interface BearState {698+ bear: Map<string, string>699+ fish: Set<string>700+ time: Date701+ query: RegExp702+}703+704+const storage: PersistStorage<BearState> = {705+ getItem: (name) => {706+ const str = localStorage.getItem(name)707+ if (!str) return null708+ return superjson.parse(str)709+ },710+ setItem: (name, value) => {711+ localStorage.setItem(name, superjson.stringify(value))712+ },713+ removeItem: (name) => localStorage.removeItem(name),714+}715+716+const initialState: BearState = {717+ bear: new Map(),718+ fish: new Set(),719+ time: new Date(),720+ query: new RegExp(''),721+}722+723+export const useBearStore = create<BearState>()(724+ persist(725+ (set) => ({726+ ...initialState,727+ // ...728+ }),729+ {730+ name: 'food-storage',731+ storage,732+ },733+ ),734+)735+```736+737+### How can I rehydrate on storage event738+739+You can use the Persist API to create your own implementation,740+similar to the example below:741+742+```ts743+type StoreWithPersist = Mutate<StoreApi<State>, [["zustand/persist", unknown]]>744+745+export const withStorageDOMEvents = (store: StoreWithPersist) => {746+ const storageEventCallback = (e: StorageEvent) => {747+ if (e.key === store.persist.getOptions().name && e.newValue) {748+ store.persist.rehydrate()749+ }750+ }751+752+ window.addEventListener('storage', storageEventCallback)753+754+ return () => {755+ window.removeEventListener('storage', storageEventCallback)756+ }757+}758+759+const useBoundStore = create(persist(...))760+withStorageDOMEvents(useBoundStore)761+```762+763+### How do I use it with TypeScript764+765+Basic typescript usage doesn't require anything special766+except for writing `create<State>()(...)` instead of `create(...)`.767+768+```tsx769+import { create } from 'zustand'770+import { persist, createJSONStorage } from 'zustand/middleware'771+772+interface MyState {773+ bears: number774+ addABear: () => void775+}776+777+export const useBearStore = create<MyState>()(778+ persist(779+ (set, get) => ({780+ bears: 0,781+ addABear: () => set({ bears: get().bears + 1 }),782+ }),783+ {784+ name: 'food-storage', // name of item in the storage (must be unique)785+ storage: createJSONStorage(() => sessionStorage), // (optional) by default the 'localStorage' is used786+ partialize: (state) => ({ bears: state.bears }),787+ },788+ ),789+)790+```791+792+### How do I use it with Map and Set793+794+In order to persist object types such as `Map` and `Set`, they will need to be converted to JSON-serializable types such as an `Array` which can be done by defining a custom `storage` engine.795+796+Let's say your state uses `Map` to handle a list of `transactions`,797+then you can convert the `Map` into an `Array` in the `storage` prop which is shown below:798+799+```ts800+801+interface BearState {802+ .803+ .804+ .805+ transactions: Map<any>806+}807+808+ storage: {809+ getItem: (name) => {810+ const str = localStorage.getItem(name);811+ if (!str) return null;812+ const existingValue = JSON.parse(str);813+ return {814+ ...existingValue,815+ state: {816+ ...existingValue.state,817+ transactions: new Map(existingValue.state.transactions),818+ }819+ }820+ },821+ setItem: (name, newValue: StorageValue<BearState>) => {822+ // functions cannot be JSON encoded823+ const str = JSON.stringify({824+ ...newValue,825+ state: {826+ ...newValue.state,827+ transactions: Array.from(newValue.state.transactions.entries()),828+ },829+ })830+ localStorage.setItem(name, str)831+ },832+ removeItem: (name) => localStorage.removeItem(name),833+ },834+```added:docs/reference/integrations/third-party-libraries.md+82 added
1+---2+title: Third-party Libraries3+nav: 364+---5+6+Zustand provides bear necessities for state management.7+Although it is great for most projects,8+some users wish to extend the library's feature set.9+This can be done using third-party libraries created by the community.10+11+> Disclaimer: These libraries may have bugs, limited maintenance,12+> or other limitations, and are not officially recommended13+> by pmndrs or the Zustand maintainers.14+> This list aims to provide a good starting point15+> for someone looking to extend Zustand's feature set.16+17+- [@colorfy-software/zfy](https://colorfy-software.gitbook.io/zfy/) — 🧸 Useful helpers for state management in React with Zustand.18+- [@csark0812/zustand-expo-devtools](https://github.com/csark0812/zustand-expo-devtools) — 🧭 Connect Zustand to Redux DevTools in Expo + React Native using the official Expo DevTools plugin system.19+- [@csark0812/zustand-getters](https://github.com/csark0812/zustand-getters) — 🔄 Make JavaScript object getters reactive in Zustand stores — define derived values with `get propertyName()` and they automatically trigger subscription updates when accessed.20+- [@davstack/store](https://www.npmjs.com/package/@davstack/store) — A zustand store factory that auto generates selectors with get/set/use methods, supports inferred types, and makes global / local state management easy.21+- [@dhmk/zustand-lens](https://github.com/dhmk083/dhmk-zustand-lens) — Lens support for Zustand.22+- [@hpkv/zustand-multiplayer](https://github.com/hpkv-io/zustand-multiplayer/tree/main/packages/zustand-multiplayer) — HPKV multiplayer middleware for building realtime collaborative applications23+- [@liveblocks/zustand](https://github.com/liveblocks/liveblocks/tree/main/packages/liveblocks-zustand) — Liveblocks middleware to make your application multiplayer.24+- [@prncss-xyz/zustand-optics](https://github.com/prncss-xyz/zustand-optics) — An adapter for [optics-ts](https://github.com/akheron/optics-ts).25+- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook) — Automatic generation of Zustand hooks with Typescript support.26+- [derive-zustand](https://github.com/zustandjs/derive-zustand) — A function to create a derived Zustand store from other Zustand stores.27+- [geschichte](https://github.com/BowlingX/geschichte) — Zustand and Immer-based hook to manage query parameters.28+- [leiten-zustand](https://github.com/hecmatyar/leiten-zustand) — Cleans your store from boilerplate for requests and data transformation.29+- [leo-query](https://github.com/steaks/leo-query) — A simple library to connect async queries to Zustand stores.30+- [mobz](https://github.com/2A5F/Mobz) — Zustand-style MobX API.31+- [ngx-zustand](https://github.com/JoaoPauloLousada/ngx-zustand) — A Zustand adapter for Angular.32+- [persist-and-sync](https://github.com/mayank1513/persist-and-sync) — Zustand middleware to easily persist and sync Zustand state between tabs/windows/iframes with same origin.33+- [shared-zustand](https://github.com/Tom-Julux/shared-zustand) — Cross-tab state sharing for Zustand.34+- [simple-zustand-devtools](https://github.com/beerose/simple-zustand-devtools) — 🐻⚛️ Inspect your Zustand store in React DevTools.35+- [solid-zustand](https://github.com/wobsoriano/solid-zustand) — State management in Solid using Zustand.36+- [treeshakable](https://github.com/react18-tools/treeshakable) — A wrapper for library creators to avoid redundant store creation.37+- [use-broadcast-ts](https://github.com/Romainlg29/use-broadcast) — Zustand middleware to share state between tabs.38+- [use-post-message-ts](https://github.com/paulschoen/use-post-message) — Zustand middleware for sharing state between cross-origin iframes via postMessage browser method.39+- [use-zustand](https://github.com/zustandjs/use-zustand) — Another custom hook to use Zustand vanilla store.40+- [vue-zustand](https://github.com/wobsoriano/vue-zustand) — State management solution for Vue based on Zustand.41+- [zoov](https://github.com/InfiniteXyy/zoov) — State management solution based on Zustand with Module-like API.42+- [zubridge](https://github.com/goosewobbler/zubridge) — Use Zustand in cross-platform apps, seamlessly. Supports Electron & Tauri.43+- [zukeeper](https://github.com/oslabs-beta/Zukeeper) — Native devtools with state and action tracking, diffing, tree display, and time travel44+- [zundo](https://github.com/charkour/zundo) — 🍜 Undo and redo middleware for Zustand, enabling time-travel in your apps.45+- [zustand-ards](https://github.com/ivoilic/zustand-ards) — 💁 Simple opinionated utilities for example alternative selector formats and default shallow hooks46+- [zustand-async-slice](https://github.com/mym0404/zustand-async-slice) — Simple Zustand utility to create Async Slice. TypeScript Fully Supported 🖖47+- [zustand-boilerplate](https://github.com/sagiereder/zustand-boilerplate) — A tool that automatically generates getters, setters and more for your zustand store.48+- [zustand-computed](https://github.com/chrisvander/zustand-computed) — A Zustand middleware to create computed states.49+- [zustand-computed-state](https://github.com/yasintz/zustand-computed-state) — Simple middleware to add computed states.50+- [zustand-constate](https://github.com/ntvinhit/zustand-constate) — Context-based state management based on Zustand and taking ideas from Constate.51+- [zustand-context](https://github.com/fredericoo/zustand-context) — Create a zustand store in React Context, containing an initial value, or use it in your components with isolated, mockable instances.52+- [zustand-create-setter-fn](https://www.npmjs.com/package/zustand-create-setter-fn) — A fully type safe utility for Zustand that allows you to easily update state using React style `setState` functions (framework agnostic, doesn't require React).53+- [zustand-di](https://github.com/charkour/zustand-di) — use react props to init zustand stores54+- [zustand-forms](https://github.com/Conduct/zustand-forms) — Fast, type safe form states as Zustand stores.55+- [zustand-hash-storage](https://github.com/MartinGamesCZ/zustand-hash-storage) — Zustand middleware for saving state into URL hash, b64 encoded (can be configured) and debounce timer.56+- [zustand-injectors](https://github.com/zustandjs/zustand-injectors) — A sweet way to lazy load slices57+- [zustand-interval-persist](https://www.npmjs.com/package/zustand-interval-persist) — An enhancement for zustand that enables automatic saving of the store's state to the specified storage at regular interval.58+- [zustand-lit](https://github.com/ennjin/zustand-lit) — A zustand adapter for lit.js (LitElement)59+- [zustand-middleware-computed-state](https://github.com/cmlarsen/zustand-middleware-computed-state) — A dead simple middleware for adding computed state to Zustand.60+- [zustand-middleware-xstate](https://github.com/biowaffeln/zustand-middleware-xstate) — A middleware for putting XState state machines into a global Zustand store.61+- [zustand-middleware-yjs](https://github.com/joebobmiles/zustand-middleware-yjs) — A middleware for synchronizing Zustand stores with Yjs.62+- [zustand-mmkv-storage](https://github.com/1mehdifaraji/zustand-mmkv-storage) — Fast, lightweight MMKV storage adapter for Zustand persist middleware in React Native.63+- [zustand-multi-persist](https://github.com/mooalot/zustand-multi-persist) — A middleware for persisting and rehydrating state to multiple storage engines.64+- [zustand-mutable](https://github.com/zustandjs/zustand-mutable) — A sweet way to use immer-like mutable updates.65+- [zustand-namespaces](https://github.com/mooalot/zustand-namespaces) — One store to rule them all. Namespaced Zustand stores.66+- [zustand-persist](https://github.com/roadmanfong/zustand-persist) — A middleware for persisting and rehydrating state.67+- [zustand-pub](https://github.com/AwesomeDevin/zustand-pub) — Cross-Application/Cross-Framework State Management And Sharing based on zustand and zustand-vue for React/Vue.68+- [zustand-querystring](https://github.com/nitedani/zustand-querystring) — A Zustand middleware that syncs the store with the querystring.69+- [zustand-rx](https://github.com/patdx/zustand-rx) — A Zustand middleware enabling you to subscribe to a store as an RxJS Observable.70+- [zustand-saga](https://github.com/Nowsta/zustand-saga) — A Zustand middleware for redux-saga (minus redux).71+- [zustand-slices](https://github.com/zustandjs/zustand-slices) — A slice utility for Zustand.72+- [zustand-store-addons](https://github.com/Diablow/zustand-store-addons) — React state management addons for Zustand.73+- [zustand-sync-tabs](https://github.com/mayank1513/zustand-sync-tabs) — Zustand middleware to easily sync Zustand state between tabs/windows/iframes with same origin.74+- [zustand-utils](https://www.npmjs.com/package/zustand-utils) — Utilities for Zustand — a `createContext` replacement, a devtools wrapper, and a store-updater factory function.75+- [zustand-valtio](https://github.com/zustandjs/zustand-valtio) — A sweet combination of Zustand and Valtio76+- [zustand-vue](https://github.com/AwesomeDevin/zustand-vue) — State management for vue (Vue3 / Vue2) based on zustand.77+- [zustand-x](https://github.com/udecode/zustand-x) — Zustand store factory for a best-in-class developer experience.78+- [zustand-xs](https://github.com/zustandjs/zustand-xs) — XState/store compabile middleware for Zustand79+- [zustand-yjs](https://github.com/tandem-pt/zustand-yjs) — Zustand stores for Yjs structures.80+- [zusteller](https://github.com/timkindberg/zusteller) — Your global state savior. "Just hooks" + Zustand.81+- [zustorm](https://github.com/mooalot/zustorm) — A simple and powerful form library for Zustand.82+- [zusty](https://github.com/oslabs-beta/Zusty) — Zustand tool to assist debugging with time travel, action logs, state snapshots, store view, render time metrics and state component tree.added:docs/reference/middlewares/combine.md+103 added
1+---2+title: combine3+description: How to create a store and get types automatically inferred4+nav: 325+---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'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/reference/middlewares/devtools.md+352 added
1+---2+title: devtools3+description: How to time-travel debug your store4+nav: 295+---6+7+# devtools8+9+`devtools` middleware lets you use [Redux DevTools Extension](https://github.com/reduxjs/redux-devtools)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+> [!IMPORTANT]13+> In order to use `devtools` from `zustand/middleware` you need to install14+> `@redux-devtools/extension` library.15+16+```js17+const nextStateCreatorFn = devtools(stateCreatorFn, devtoolsOptions)18+```19+20+- [Types](#types)21+ - [Signature](#signature)22+ - [Mutator](#mutator)23+- [Reference](#reference)24+- [Usage](#usage)25+ - [Debugging a store](#debugging-a-store)26+ - [Debugging a Slices pattern based store](#debugging-a-slices-pattern-based-store)27+ - [Filtering actions with actionsDenylist](#filtering-actions-with-actionsdenylist)28+ - [Cleanup](#cleanup)29+- [Troubleshooting](#troubleshooting)30+ - [Only one store is displayed](#only-one-store-is-displayed)31+ - [Action names are labeled as 'anonymous'](#all-action-names-are-labeled-as-anonymous)32+33+## Types34+35+### Signature36+37+```ts38+devtools<T>(stateCreatorFn: StateCreator<T, [], []>, devtoolsOptions?: DevtoolsOptions): StateCreator<T, [['zustand/devtools', never]], []>39+```40+41+### Mutator42+43+<!-- prettier-ignore-start -->44+```ts45+['zustand/devtools', never]46+```47+<!-- prettier-ignore-end -->48+49+## Reference50+51+### `devtools(stateCreatorFn, devtoolsOptions)`52+53+#### Parameters54+55+- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.56+ Usually, you will return an object with the methods you want to expose.57+- **optional** `devtoolsOptions`: An object to define `Redux Devtools` options.58+ - **optional** `name`: A custom identifier for the connection in the Redux DevTools.59+ - **optional** `enabled`: Defaults to `true` when is on development mode, and defaults to `false`60+ when is on production mode. Enables or disables the Redux DevTools integration61+ for this store.62+ - **optional** `anonymousActionType`: Defaults to the inferred action type or `anonymous` if63+ unavailable. A string to use as the action type for anonymous mutations in the Redux DevTools.64+ - **optional** `store`: A custom identifier for the store in the Redux DevTools.65+ - **optional** `actionsDenylist`: A string or array of strings (regex patterns) that specify which66+ actions should be filtered out from Redux DevTools. This option is passed directly to Redux DevTools67+ for filtering. For example, `['secret.*']` will filter out all actions starting with "secret".68+69+#### Returns70+71+`devtools` returns a state creator function.72+73+## Usage74+75+### Debugging a store76+77+This example shows you how you can use `Redux Devtools` to debug a store78+79+```ts80+import { create, StateCreator } from 'zustand'81+import { devtools } from 'zustand/middleware'82+83+type JungleStore = {84+ bears: number85+ addBear: () => void86+ fishes: number87+ addFish: () => void88+}89+90+const useJungleStore = create<JungleStore>()(91+ devtools((set) => ({92+ bears: 0,93+ addBear: () =>94+ set((state) => ({ bears: state.bears + 1 }), undefined, 'jungle/addBear'),95+ fishes: 0,96+ addFish: () =>97+ set(98+ (state) => ({ fishes: state.fishes + 1 }),99+ undefined,100+ 'jungle/addFish',101+ ),102+ })),103+)104+```105+106+### Debugging a Slices pattern based store107+108+This example shows you how you can use `Redux Devtools` to debug a Slices pattern based store109+110+```ts111+import { create, StateCreator } from 'zustand'112+import { devtools } from 'zustand/middleware'113+114+type BearSlice = {115+ bears: number116+ addBear: () => void117+}118+119+type FishSlice = {120+ fishes: number121+ addFish: () => void122+}123+124+type JungleStore = BearSlice & FishSlice125+126+const createBearSlice: StateCreator<127+ JungleStore,128+ [['zustand/devtools', never]],129+ [],130+ BearSlice131+> = (set) => ({132+ bears: 0,133+ addBear: () =>134+ set(135+ (state) => ({ bears: state.bears + 1 }),136+ undefined,137+ 'jungle:bear/addBear',138+ ),139+})140+141+const createFishSlice: StateCreator<142+ JungleStore,143+ [['zustand/devtools', never]],144+ [],145+ FishSlice146+> = (set) => ({147+ fishes: 0,148+ addFish: () =>149+ set(150+ (state) => ({ fishes: state.fishes + 1 }),151+ undefined,152+ 'jungle:fish/addFish',153+ ),154+})155+156+const useJungleStore = create<JungleStore>()(157+ devtools((...args) => ({158+ ...createBearSlice(...args),159+ ...createFishSlice(...args),160+ })),161+)162+```163+164+### Filtering actions with actionsDenylist165+166+You can filter out specific actions from Redux DevTools using the `actionsDenylist` option. This is useful for hiding internal or sensitive actions from the DevTools timeline.167+168+```ts169+import { create } from 'zustand'170+import { devtools } from 'zustand/middleware'171+172+type Store = {173+ user: string | null174+ token: string | null175+ login: (user: string, token: string) => void176+ logout: () => void177+ updateData: () => void178+}179+180+const useStore = create<Store>()(181+ devtools(182+ (set) => ({183+ user: null,184+ token: null,185+ login: (user, token) => set({ user, token }, undefined, 'auth/login'),186+ logout: () => set({ user: null, token: null }, undefined, 'auth/logout'),187+ updateData: () =>188+ set({ user: 'updated' }, undefined, 'internal/updateData'),189+ }),190+ {191+ name: 'AuthStore',192+ // Filter out actions matching these regex patterns193+ actionsDenylist: ['internal/.*'], // Hides all 'internal/*' actions194+ },195+ ),196+)197+```198+199+You can also use a single regex string:200+201+```ts202+const useStore = create<Store>()(203+ devtools(204+ (set) => ({205+ // ... state and actions206+ }),207+ {208+ name: 'MyStore',209+ actionsDenylist: 'secret.*', // Hides all actions starting with 'secret'210+ },211+ ),212+)213+```214+215+> [!NOTE]216+> The `actionsDenylist` option uses regex pattern matching and is handled directly by Redux DevTools Extension.217+> All actions are still sent to DevTools, but matching actions are filtered from the display.218+219+### Cleanup220+221+When a store is no longer needed, you can clean up the Redux DevTools connection by calling the `cleanup` method on the store:222+223+```ts224+import { create } from 'zustand'225+import { devtools } from 'zustand/middleware'226+227+const useStore = create(228+ devtools((set) => ({229+ count: 0,230+ increment: () => set((state) => ({ count: state.count + 1 })),231+ })),232+)233+234+// When you're done with the store, clean it up235+useStore.devtools.cleanup()236+```237+238+This is particularly useful in applications that wrap store in context or create multiple stores dynamically.239+240+## Troubleshooting241+242+### Only one store is displayed243+244+By default, `Redux Devtools` only show one store at a time, so in order to see other stores you245+need to use store selector and choose a different store.246+247+### All action names are labeled as 'anonymous'248+249+If an action type name is not provided, it is defaulted to "anonymous". You can customize this250+default value by providing a `anonymousActionType` parameter:251+252+For instance the next example doesn't have action type name:253+254+```ts255+import { create, StateCreator } from 'zustand'256+import { devtools } from 'zustand/middleware'257+258+type BearSlice = {259+ bears: number260+ addBear: () => void261+}262+263+type FishSlice = {264+ fishes: number265+ addFish: () => void266+}267+268+type JungleStore = BearSlice & FishSlice269+270+const createBearSlice: StateCreator<271+ JungleStore,272+ [['zustand/devtools', never]],273+ [],274+ BearSlice275+> = (set) => ({276+ bears: 0,277+ addBear: () => set((state) => ({ bears: state.bears + 1 })),278+ eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),279+})280+281+const createFishSlice: StateCreator<282+ JungleStore,283+ [['zustand/devtools', never]],284+ [],285+ FishSlice286+> = (set) => ({287+ fishes: 0,288+ addFish: () => set((state) => ({ fishes: state.fishes + 1 })),289+})290+291+const useJungleStore = create<JungleStore>()(292+ devtools((...args) => ({293+ ...createBearSlice(...args),294+ ...createFishSlice(...args),295+ })),296+)297+```298+299+In order to fix the previous example, we need to provide an action type name as the third parameter.300+Additionally, to preserve the default behavior of the replacement logic, the second parameter301+should be set to `undefined`.302+303+Here's the fixed previous example304+305+```ts306+import { create, StateCreator } from 'zustand'307+308+type BearSlice = {309+ bears: number310+ addBear: () => void311+}312+313+type FishSlice = {314+ fishes: number315+ addFish: () => void316+}317+318+type JungleStore = BearSlice & FishSlice319+320+const createBearSlice: StateCreator<321+ JungleStore,322+ [['zustand/devtools', never]],323+ [],324+ BearSlice325+> = (set) => ({326+ bears: 0,327+ addBear: () =>328+ set((state) => ({ bears: state.bears + 1 }), undefined, 'bear/addBear'),329+})330+331+const createFishSlice: StateCreator<332+ JungleStore,333+ [['zustand/devtools', never]],334+ [],335+ FishSlice336+> = (set) => ({337+ fishes: 0,338+ addFish: () =>339+ set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fish/addFish'),340+})341+342+const useJungleStore = create<JungleStore>()(343+ devtools((...args) => ({344+ ...createBearSlice(...args),345+ ...createFishSlice(...args),346+ })),347+)348+```349+350+> [!IMPORTANT]351+> Do not set the second parameter to `true` or `false` unless you want to override the default352+> replacement logicadded:docs/reference/middlewares/immer.md+239 added
1+---2+title: immer3+description: How to perform immutable updates in a store without boilerplate code4+nav: 315+---6+7+# immer8+9+`immer` middleware lets you perform immutable updates.10+11+> [!IMPORTANT]12+> In order to use `immer` from `zustand/middleware/immer` you need to install13+> `immer` library.14+15+```js16+const nextStateCreatorFn = immer(stateCreatorFn)17+```18+19+- [Types](#types)20+ - [Signature](#signature)21+ - [Mutator](#mutator)22+- [Reference](#reference)23+- [Usage](#usage)24+- [Troubleshooting](#troubleshooting)25+26+## Types27+28+### Signature29+30+```ts31+immer<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/immer', never]], []>32+```33+34+### Mutator35+36+<!-- prettier-ignore-start -->37+```ts38+['zustand/immer', never]39+```40+<!-- prettier-ignore-end -->41+42+## Reference43+44+### `immer(stateCreatorFn)`45+46+#### Parameters47+48+- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.49+ Usually, you will return an object with the methods you want to expose.50+51+#### Returns52+53+`immer` returns a state creator function.54+55+## Usage56+57+### Updating state without boilerplate code58+59+In the next example, we're going to update the `person` object. Since it's a nested object, we need60+to create a copy of the entire object before making the update.61+62+```ts63+import { createStore } from 'zustand/vanilla'64+65+type PersonStoreState = {66+ person: { firstName: string; lastName: string; email: string }67+}68+69+type PersonStoreActions = {70+ setPerson: (71+ nextPerson: (72+ person: PersonStoreState['person'],73+ ) => PersonStoreState['person'] | PersonStoreState['person'],74+ ) => void75+}76+77+type PersonStore = PersonStoreState & PersonStoreActions78+79+const personStore = createStore<PersonStore>()((set) => ({80+ person: {81+ firstName: 'Barbara',82+ lastName: 'Hepworth',83+ email: 'bhepworth@sculpture.com',84+ },85+ setPerson: (nextPerson) =>86+ set((state) => ({87+ person:88+ typeof nextPerson === 'function'89+ ? nextPerson(state.person)90+ : nextPerson,91+ })),92+}))93+94+const $firstNameInput = document.getElementById(95+ 'first-name',96+) as HTMLInputElement97+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement98+const $emailInput = document.getElementById('email') as HTMLInputElement99+const $result = document.getElementById('result') as HTMLDivElement100+101+function handleFirstNameChange(event: Event) {102+ personStore.getState().setPerson((person) => ({103+ ...person,104+ firstName: (event.target as any).value,105+ }))106+}107+108+function handleLastNameChange(event: Event) {109+ personStore.getState().setPerson((person) => ({110+ ...person,111+ lastName: (event.target as any).value,112+ }))113+}114+115+function handleEmailChange(event: Event) {116+ personStore.getState().setPerson((person) => ({117+ ...person,118+ email: (event.target as any).value,119+ }))120+}121+122+$firstNameInput.addEventListener('input', handleFirstNameChange)123+$lastNameInput.addEventListener('input', handleLastNameChange)124+$emailInput.addEventListener('input', handleEmailChange)125+126+const render: Parameters<typeof personStore.subscribe>[0] = (state) => {127+ $firstNameInput.value = state.person.firstName128+ $lastNameInput.value = state.person.lastName129+ $emailInput.value = state.person.email130+131+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`132+}133+134+render(personStore.getInitialState(), personStore.getInitialState())135+136+personStore.subscribe(render)137+```138+139+Here's the `html` code140+141+```html142+<label style="display: block">143+ First name:144+ <input id="first-name" />145+</label>146+<label style="display: block">147+ Last name:148+ <input id="last-name" />149+</label>150+<label style="display: block">151+ Email:152+ <input id="email" />153+</label>154+<p id="result"></p>155+```156+157+To avoid manually copying the entire object before making updates, we'll use the `immer`158+middleware.159+160+```ts161+import { createStore } from 'zustand/vanilla'162+import { immer } from 'zustand/middleware/immer'163+164+type PersonStoreState = {165+ person: { firstName: string; lastName: string; email: string }166+}167+168+type PersonStoreActions = {169+ setPerson: (170+ nextPerson: (171+ person: PersonStoreState['person'],172+ ) => PersonStoreState['person'] | PersonStoreState['person'],173+ ) => void174+}175+176+type PersonStore = PersonStoreState & PersonStoreActions177+178+const personStore = createStore<PersonStore>()(179+ immer((set) => ({180+ person: {181+ firstName: 'Barbara',182+ lastName: 'Hepworth',183+ email: 'bhepworth@sculpture.com',184+ },185+ setPerson: (nextPerson) =>186+ set((state) => {187+ state.person =188+ typeof nextPerson === 'function'189+ ? nextPerson(state.person)190+ : nextPerson191+ }),192+ })),193+)194+195+const $firstNameInput = document.getElementById(196+ 'first-name',197+) as HTMLInputElement198+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement199+const $emailInput = document.getElementById('email') as HTMLInputElement200+const $result = document.getElementById('result') as HTMLDivElement201+202+function handleFirstNameChange(event: Event) {203+ personStore.getState().setPerson((person) => {204+ person.firstName = (event.target as any).value205+ })206+}207+208+function handleLastNameChange(event: Event) {209+ personStore.getState().setPerson((person) => {210+ person.lastName = (event.target as any).value211+ })212+}213+214+function handleEmailChange(event: Event) {215+ personStore.getState().setPerson((person) => {216+ person.email = (event.target as any).value217+ })218+}219+220+$firstNameInput.addEventListener('input', handleFirstNameChange)221+$lastNameInput.addEventListener('input', handleLastNameChange)222+$emailInput.addEventListener('input', handleEmailChange)223+224+const render: Parameters<typeof personStore.subscribe>[0] = (state) => {225+ $firstNameInput.value = state.person.firstName226+ $lastNameInput.value = state.person.lastName227+ $emailInput.value = state.person.email228+229+ $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`230+}231+232+render(personStore.getInitialState(), personStore.getInitialState())233+234+personStore.subscribe(render)235+```236+237+## Troubleshooting238+239+TBDadded:docs/reference/middlewares/persist.md+988 added
1+---2+title: persist3+description: How to persist a store4+nav: 285+---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/reference/middlewares/redux.md+172 added
1+---2+title: redux3+description: How to use actions and reducers in a store4+nav: 305+---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'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 & {74+ dispatch: (action: PersonStoreAction) => PersonStoreAction75+}76+77+const personStoreReducer = (78+ state: PersonStoreState,79+ action: PersonStoreAction,80+) => {81+ switch (action.type) {82+ case 'person/setFirstName': {83+ return { ...state, firstName: action.firstName }84+ }85+ case 'person/setLastName': {86+ return { ...state, lastName: action.lastName }87+ }88+ case 'person/setEmail': {89+ return { ...state, email: action.email }90+ }91+ default: {92+ return state93+ }94+ }95+}96+97+const personStoreInitialState: PersonStoreState = {98+ firstName: 'Barbara',99+ lastName: 'Hepworth',100+ email: 'bhepworth@sculpture.com',101+}102+103+const personStore = createStore<PersonStore>()(104+ redux(personStoreReducer, personStoreInitialState),105+)106+107+const $firstNameInput = document.getElementById(108+ 'first-name',109+) as HTMLInputElement110+const $lastNameInput = document.getElementById('last-name') as HTMLInputElement111+const $emailInput = document.getElementById('email') as HTMLInputElement112+const $result = document.getElementById('result') as HTMLDivElement113+114+function handleFirstNameChange(event: Event) {115+ personStore.dispatch({116+ type: 'person/setFirstName',117+ firstName: (event.target as any).value,118+ })119+}120+121+function handleLastNameChange(event: Event) {122+ personStore.dispatch({123+ type: 'person/setLastName',124+ lastName: (event.target as any).value,125+ })126+}127+128+function handleEmailChange(event: Event) {129+ personStore.dispatch({130+ type: 'person/setEmail',131+ email: (event.target as any).value,132+ })133+}134+135+$firstNameInput.addEventListener('input', handleFirstNameChange)136+$lastNameInput.addEventListener('input', handleLastNameChange)137+$emailInput.addEventListener('input', handleEmailChange)138+139+const render: Parameters<typeof personStore.subscribe>[0] = (person) => {140+ $firstNameInput.value = person.firstName141+ $lastNameInput.value = person.lastName142+ $emailInput.value = person.email143+144+ $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`145+}146+147+render(personStore.getInitialState(), personStore.getInitialState())148+149+personStore.subscribe(render)150+```151+152+Here's the `html` code153+154+```html155+<label style="display: block">156+ First name:157+ <input id="first-name" />158+</label>159+<label style="display: block">160+ Last name:161+ <input id="last-name" />162+</label>163+<label style="display: block">164+ Email:165+ <input id="email" />166+</label>167+<p id="result"></p>168+```169+170+## Troubleshooting171+172+TBDadded:docs/reference/middlewares/subscribe-with-selector.md+121 added
1+---2+title: subscribeWithSelector3+description: How to subscribe to granular store updates in a store4+nav: 335+---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'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+TBDadded:docs/reference/migrations/migrating-to-v4.md+362 added
1+---2+title: Migrating to v43+nav: 384+---5+6+The only breaking changes are in types.7+If you are using Zustand with TypeScript8+or JSDoc type annotations,9+this guide applies.10+Otherwise, no migration is required.11+12+Also, it's recommended to first read13+the new [TypeScript Guide](../../learn/guides/advanced-typescript.md),14+so that the migration is easier to understand.15+16+In addition to this migration guide,17+you can also check the18+[diff](https://github.com/pmndrs/zustand/compare/v3.7.2...v4.0.0?short_path=37e5b4c#diff-c21e24854115b390eccde717da83f91feb2d5927a76c1485e5f0fdd0135c2afa)19+of the test files in the Zustand repository from v3 to v4.20+21+## `create`22+23+**Applicable imports**24+25+```ts26+import create from 'zustand'27+import create from 'zustand/vanilla'28+```29+30+**Change**31+32+```diff33+- create:34+- < State35+- , StoreSetState = StoreApi<State>["set"]36+- , StoreGetState = StoreApi<State>["get"]37+- , Store = StoreApi<State>38+- >39+- (f: ...) => ...40++ create:41++ { <State>(): (f: ...) => ...42++ , <State, Mutators>(f: ...) => ...43++ }44+```45+46+**Migration**47+48+If you are not passing any type parameters to `create`,49+no migration is required.50+51+If you are using a "leaf" middleware like `combine` or `redux`,52+remove all type parameters from `create`.53+54+Else, replace `create<T, ...>(...)` with `create<T>()(...)`.55+56+## `StateCreator`57+58+**Applicable imports**59+60+```ts61+import type { StateCreator } from 'zustand'62+import type { StateCreator } from 'zustand/vanilla'63+```64+65+**Change**66+67+```diff68+- type StateCreator69+- < State70+- , StoreSetState = StoreApi<State>["set"]71+- , StoreGetState = StoreApi<State>["get"]72+- , Store = StoreApi<State>73+- > =74+- ...75++ type StateCreator76++ < State77++ , InMutators extends [StoreMutatorIdentifier, unknown][] = []78++ , OutMutators extends [StoreMutatorIdentifier, unknown][] = []79++ , Return = State80++ > =81++ ...82+```83+84+**Migration**85+86+If you are using `StateCreator`,87+you are likely authoring a middleware88+or using the "slices" pattern.89+For that check the90+[Authoring middlewares and advanced usage](../../learn/guides/advanced-typescript.md#authoring-middlewares-and-advanced-usage)91+and [Common recipes](../../learn/guides/advanced-typescript.md#common-recipes)92+sections of the TypeScript Guide.93+94+## `PartialState`95+96+**Applicable imports**97+98+```ts99+import type { PartialState } from 'zustand'100+import type { PartialState } from 'zustand/vanilla'101+```102+103+**Change**104+105+```diff106+- type PartialState107+- < T extends State108+- , K1 extends keyof T = keyof T109+- , K2 extends keyof T = K1110+- , K3 extends keyof T = K2111+- , K4 extends keyof T = K3112+- > =113+- | (Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)114+- | ((state: T) => Pick<T, K1> | Pick<T, K2> | Pick<T, K3> | Pick<T, K4> | T)115++ type PartialState<T> =116++ | Partial<T>117++ | ((state: T) => Partial<T>)118+```119+120+**Migration**121+122+Replace `PartialState<T, ...>` with `PartialState<T>`123+and preferably turn on [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes)124+in your `tsconfig.json`:125+126+```json127+{128+ "compilerOptions": {129+ "exactOptionalPropertyTypes": true130+ }131+}132+```133+134+We're no longer using the trick to disallow `{ foo: undefined }`135+to be assigned to `Partial<{ foo: string }>`.136+Instead, we're relying on the users to turn on `exactOptionalPropertyTypes`.137+138+## `useStore`139+140+**Applicable imports**141+142+```ts143+import { useStore } from 'zustand'144+import { useStore } from 'zustand/react'145+```146+147+**Change**148+149+```diff150+- useStore:151+- { <State>(store: StoreApi<State>): State152+- , <State, StateSlice>153+- ( store: StoreApi<State>154+- , selector: StateSelector<State, StateSlice>,155+- , equals?: EqualityChecker<StateSlice>156+- ): StateSlice157+- }158++ useStore:159++ <Store, StateSlice = ExtractState<Store>>160++ ( store: Store161++ , selector?: StateSelector<State, StateSlice>,162++ , equals?: EqualityChecker<StateSlice>163++ )164++ => StateSlice165+```166+167+**Migration**168+169+If you are not passing any type parameters to `useStore`,170+no migration is required.171+172+If you are,173+it's recommended to remove all the type parameters,174+or pass the **store** type instead of the **state** type as the first parameter.175+176+## `UseBoundStore`177+178+**Applicable imports**179+180+```ts181+import type { UseBoundStore } from 'zustand'182+import type { UseBoundStore } from 'zustand/react'183+```184+185+**Change**186+187+```diff188+- type UseBoundStore<189+- State,190+- Store = StoreApi<State>191+- > =192+- & { (): T193+- , <StateSlice>194+- ( selector: StateSelector<State, StateSlice>195+- , equals?: EqualityChecker<StateSlice>196+- ): U197+- }198+- & Store199++ type UseBoundStore<Store> =200++ & (<StateSlice = ExtractState<S>>201++ ( selector?: (state: ExtractState<S>) => StateSlice202++ , equals?: (a: StateSlice, b: StateSlice) => boolean203++ ) => StateSlice204++ )205++ & S206+```207+208+**Migration**209+210+Replace `UseBoundStore<T>` with `UseBoundStore<StoreApi<T>>`,211+and `UseBoundStore<T, S>` with `UseBoundStore<S>`212+213+## `UseContextStore`214+215+**Applicable imports**216+217+```ts218+import type { UseContextStore } from 'zustand/context'219+```220+221+**Change**222+223+```diff224+- type UseContextStore225+```226+227+**Migration**228+229+Use `typeof MyContext.useStore` instead230+231+## `createContext`232+233+**Applicable imports**234+235+```ts236+import createContext from 'zustand/context'237+```238+239+**Change**240+241+```diff242+ createContext:243+- <State, Store = StoreApi<State>>() => ...244++ <Store>() => ...245+```246+247+**Migration**248+249+Replace `createContext<T>()` with `createContext<StoreApi<T>>()`,250+and `createContext<T, S>()` with `createContext<S>()`.251+252+## `combine`, `devtools`, `subscribeWithSelector`253+254+**Applicable imports**255+256+```ts257+import { combine } from 'zustand/middleware'258+import { devtools } from 'zustand/middleware'259+import { subscribeWithSelector } from 'zustand/middleware'260+```261+262+**Change**263+264+```diff265+- combine:266+- <T, U>(...) => ...267++ combine:268++ <T, U, Mps, Mcs>(...) => ...269+270+- devtools:271+- <T>(...) => ...272++ devtools:273++ <T, Mps, Mcs>(...) => ...274+275+- subscribeWithSelector:276+- <T>(...) => ...277++ subscribeWithSelector:278++ <T, Mps, Mcs>(...) => ...279+```280+281+**Migration**282+283+If you are not passing any type parameters284+to `combine`, `devtools`, or `subscribeWithSelector`,285+no migration is required.286+287+If you are,288+remove all the type parameters,289+as they are inferred automatically.290+291+## `persist`292+293+**Applicable imports**294+295+```ts296+import { persist } from 'zustand/middleware'297+```298+299+**Change**300+301+```diff302+- persist:303+- <T, U = Partial<T>>(...) => ...304++ persist:305++ <T, Mps, Mcs, U = T>(...) => ...306+```307+308+**Migration**309+310+If you are passing any type parameters,311+remove them as they are inferred automatically.312+313+Next, if you are passing the `partialize` option,314+there is no further steps required for migration.315+316+If you are **not** passing the `partialize` option,317+you might see some compilation errors.318+If you do not see any,319+there is no further migration required.320+321+The type of partialized state is now `T` instead of `Partial<T>`,322+which aligns with the runtime behavior of the default `partialize`,323+which is an identity (`s => s`).324+325+If you see some compilation errors,326+you have to find and fix the errors yourself,327+because they might be indicative of unsound code.328+Alternatively, the workaround will be passing329+`s => s as Partial<typeof s>` to `partialize`.330+If your partialized state is truly `Partial<T>`,331+you should not encounter any bugs.332+333+The runtime behavior has not changed,334+only the types are now correct.335+336+## `redux`337+338+**Applicable imports**339+340+```ts341+import { redux } from 'zustand/middleware'342+```343+344+**Change**345+346+```diff347+- redux:348+- <T, A>(...) => ...349++ redux:350++ <T, A, Mps, Mcs>(...) => ...351+```352+353+**Migration**354+355+If you are not passing any type parameters to `redux`,356+no migration is required.357+358+If you are,359+remove all the type parameters,360+and annotate only the second (action) parameter.361+That is, replace `redux<T, A>((state, action) => ..., ...)`362+with `redux((state, action: A) => ..., ...)`.added:docs/reference/migrations/migrating-to-v5.md+241 added
1+---2+title: How to Migrate to v5 from v43+nav: 374+---5+6+# How to Migrate to v5 from v47+8+We highly recommend to update to the latest version of v4, before migrating to v5. It will show all deprecation warnings without breaking your app.9+10+## Changes in v511+12+- Drop default exports13+- Drop deprecated features14+- Make React 18 the minimum required version15+- Make use-sync-external-store a peer dependency (required for `createWithEqualityFn` and `useStoreWithEqualityFn` in `zustand/traditional`)16+- Make TypeScript 4.5 the minimum required version17+- Drop UMD/SystemJS support18+- Organize entry points in the package.json19+- Drop ES5 support20+- Stricter types when setState's replace flag is set21+- Persist middleware behavioral change22+- Other small improvements (technically breaking changes)23+24+## Migration Guide25+26+### Using custom equality functions such as `shallow`27+28+The `create` function in v5 does not support customizing equality function.29+30+If you use custom equality function such as `shallow`,31+the easiest migration is to use `createWithEqualityFn`.32+33+```js34+// v435+import { create } from 'zustand'36+import { shallow } from 'zustand/shallow'37+38+const useCountStore = create((set) => ({39+ count: 0,40+ text: 'hello',41+ // ...42+}))43+44+const Component = () => {45+ const { count, text } = useCountStore(46+ (state) => ({47+ count: state.count,48+ text: state.text,49+ }),50+ shallow,51+ )52+ // ...53+}54+```55+56+That can be done with `createWithEqualityFn` in v5:57+58+```bash59+npm install use-sync-external-store60+```61+62+```js63+// v564+import { createWithEqualityFn as create } from 'zustand/traditional'65+66+// The rest is the same as v467+```68+69+Alternatively, for the `shallow` use case, you can use `useShallow` hook:70+71+```js72+// v573+import { create } from 'zustand'74+import { useShallow } from 'zustand/shallow'75+76+const useCountStore = create((set) => ({77+ count: 0,78+ text: 'hello',79+ // ...80+}))81+82+const Component = () => {83+ const { count, text } = useCountStore(84+ useShallow((state) => ({85+ count: state.count,86+ text: state.text,87+ })),88+ )89+ // ...90+}91+```92+93+### Requiring stable selector outputs94+95+There is a behavioral change in v5 to match React default behavior.96+If a selector returns a new reference, it may cause infinite loops.97+98+For example, this may cause infinite loops.99+100+```js101+// v4102+const [searchValue, setSearchValue] = useStore((state) => [103+ state.searchValue,104+ state.setSearchValue,105+])106+```107+108+The error message will be something like this:109+110+```plaintext111+Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.112+```113+114+To fix it, use the `useShallow` hook, which will return a stable reference.115+116+```js117+// v5118+import { useShallow } from 'zustand/shallow'119+120+const [searchValue, setSearchValue] = useStore(121+ useShallow((state) => [state.searchValue, state.setSearchValue]),122+)123+```124+125+Here's another example that may cause infinite loops.126+127+```js128+// v4129+const action = useMainStore((state) => {130+ return state.action ?? () => {}131+})132+```133+134+To fix it, make sure the selector function returns a stable reference.135+136+```js137+// v5138+139+const FALLBACK_ACTION = () => {}140+141+const action = useMainStore((state) => {142+ return state.action ?? FALLBACK_ACTION143+})144+```145+146+Alternatively, if you need v4 behavior, `createWithEqualityFn` will do.147+148+```js149+// v5150+import { createWithEqualityFn as create } from 'zustand/traditional'151+```152+153+### Stricter types when setState's replace flag is set (Typescript only)154+155+```diff156+- setState:157+- (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean | undefined) => void;158++ setState:159++ (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: false) => void;160++ (state: T | ((state: T) => T), replace: true) => void;161+```162+163+If you are not using the `replace` flag, no migration is required.164+165+If you are using the `replace` flag and it's set to `true`, you must provide a complete state object.166+This change ensures that `store.setState({}, true)` (which results in an invalid state) is no longer considered valid.167+168+**Examples:**169+170+```ts171+// Partial state update (valid)172+store.setState({ key: 'value' })173+174+// Complete state replacement (valid)175+store.setState({ key: 'value' }, true)176+177+// Incomplete state replacement (invalid)178+store.setState({}, true) // Error179+```180+181+#### Handling Dynamic `replace` Flag182+183+If the value of the `replace` flag is dynamic and determined at runtime, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:184+185+```ts186+const replaceFlag = Math.random() > 0.5187+const args = [{ bears: 5 }, replaceFlag] as Parameters<188+ typeof useBearStore.setState189+>190+store.setState(...args)191+```192+193+#### Persist middleware no longer stores item at store creation194+195+Previously, the `persist` middleware stored the initial state during store creation. This behavior has been removed in v5 (and v4.5.5).196+197+For example, in the following code, the initial state is stored in the storage.198+199+```js200+// v4201+import { create } from 'zustand'202+import { persist } from 'zustand/middleware'203+204+const useCountStore = create(205+ persist(206+ () => ({207+ count: Math.floor(Math.random() * 1000),208+ }),209+ {210+ name: 'count',211+ },212+ ),213+)214+```215+216+In v5, this is no longer the case, and you need to explicitly set the state after store creation.217+218+```js219+// v5220+import { create } from 'zustand'221+import { persist } from 'zustand/middleware'222+223+const useCountStore = create(224+ persist(225+ () => ({226+ count: 0,227+ }),228+ {229+ name: 'count',230+ },231+ ),232+)233+useCountStore.setState({234+ count: Math.floor(Math.random() * 1000),235+})236+```237+238+## Links239+240+- https://github.com/pmndrs/zustand/pull/2138241+- https://github.com/pmndrs/zustand/pull/2580added:docs/reference/previous-versions/zustand-v3-create-context.md+145 added
1+---2+title: createContext from zustand/context3+nav: 394+---5+6+A special `createContext` is provided since v3.5,7+which avoids misusing the store hook.8+9+> **Note**: This function is deprecated in v4 and will be removed in v5. See [Migration](#migration).10+11+```jsx12+import create from 'zustand'13+import createContext from 'zustand/context'14+15+const { Provider, useStore } = createContext()16+17+const createStore = () => create(...)18+19+const App = () => (20+ <Provider createStore={createStore}>21+ ...22+ </Provider>23+)24+25+const Component = () => {26+ const state = useStore()27+ const slice = useStore(selector)28+ ...29+```30+31+## createContext usage in real components32+33+```jsx34+import create from "zustand";35+import createContext from "zustand/context";36+37+// Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.38+39+const { Provider, useStore } = createContext();40+41+const createStore = () =>42+ create((set) => ({43+ bears: 0,44+ increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),45+ removeAllBears: () => set({ bears: 0 })46+ }));47+48+const Button = () => {49+ return (50+ {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}51+ <Provider createStore={createStore}>52+ <ButtonChild />53+ </Provider>54+ );55+};56+57+const ButtonChild = () => {58+ const state = useStore();59+ return (60+ <div>61+ {state.bears}62+ <button63+ onClick={() => {64+ state.increasePopulation();65+ }}66+ >67+ +68+ </button>69+ </div>70+ );71+};72+73+export default function App() {74+ return (75+ <div className="App">76+ <Button />77+ <Button />78+ </div>79+ );80+}81+```82+83+## createContext usage with initialization from props84+85+```tsx86+import create from 'zustand'87+import createContext from 'zustand/context'88+89+const { Provider, useStore } = createContext()90+91+export default function App({ initialBears }) {92+ return (93+ <Provider94+ createStore={() =>95+ create((set) => ({96+ bears: initialBears,97+ increase: () => set((state) => ({ bears: state.bears + 1 })),98+ }))99+ }100+ >101+ <Button />102+ </Provider>103+ )104+}105+```106+107+## Migration108+109+Discussion: https://github.com/pmndrs/zustand/discussions/1276110+111+Here's the new context usage with v4 API.112+113+```jsx114+import { createContext, useContext, useRef } from 'react'115+import { createStore, useStore } from 'zustand'116+117+const StoreContext = createContext(null)118+119+const StoreProvider = ({ children }) => {120+ const storeRef = useRef()121+ if (storeRef.current === null) {122+ storeRef.current = createStore((set) => ({123+ // ...124+ }))125+ }126+ return (127+ <StoreContext.Provider value={storeRef.current}>128+ {children}129+ </StoreContext.Provider>130+ )131+}132+133+const useStoreInContext = (selector) => {134+ const store = useContext(StoreContext)135+ if (!store) {136+ throw new Error('Missing StoreProvider')137+ }138+ return useStore(store, selector)139+}140+```141+142+Or reach out to some third-party libraries that provide Zustand v3-like APIs:143+144+- <https://github.com/charkour/zustand-di>145+- <https://github.com/arvinxx/zustand-utils>added:docs/reference/index.md+53 added
1+---2+title: Reference3+description: API-first reference for stores, hooks, middlewares, and integrations.4+---5+6+## APIs7+8+Core functions for creating and configuring stores.9+10+- [`create`](/reference/apis/create.md) — Create a store bound to React via hooks.11+- [`createStore`](/reference/apis/create-store.md) — Create a standalone store without React.12+- [`createWithEqualityFn`](/reference/apis/create-with-equality-fn.md) — Like `create`, but with a custom equality function.13+- [`shallow`](/reference/apis/shallow.md) — Utility for shallow comparison of objects and arrays.14+15+## Hooks16+17+React hooks for reading and subscribing to store state.18+19+- [`useStore`](/reference/hooks/use-store.md) — Access and subscribe to a vanilla store from a React component.20+- [`useStoreWithEqualityFn`](/reference/hooks/use-store-with-equality-fn.md) — Like `useStore`, but with a custom equality function.21+- [`useShallow`](/reference/hooks/use-shallow.md) — Derive a stable reference from a selector using shallow comparison.22+23+## Middlewares24+25+Composable middleware functions for extending store behavior.26+27+- [`persist`](/reference/middlewares/persist.md) — Persist and rehydrate state using `localStorage` or a custom storage engine.28+- [`devtools`](/reference/middlewares/devtools.md) — Connect a store to Redux DevTools for time-travel debugging.29+- [`redux`](/reference/middlewares/redux.md) — Use a reducer and dispatch pattern similar to Redux.30+- [`immer`](/reference/middlewares/immer.md) — Write state updates with mutable syntax using Immer.31+- [`combine`](/reference/middlewares/combine.md) — Combine separate state slices into a single store with inferred types.32+- [`subscribeWithSelector`](/reference/middlewares/subscribe-with-selector.md) — Subscribe to a slice of state with selector and equality support.33+34+## Integrations35+36+In-depth guides for using Zustand alongside third-party libraries.37+38+- [Persisting store data](/reference/integrations/persisting-store-data.md) — Detailed guide to the `persist` middleware and storage adapters.39+- [Immer middleware](/reference/integrations/immer-middleware.md) — Detailed guide to the `immer` middleware.40+- [Third-party libraries](/reference/integrations/third-party-libraries.md) — Using Zustand with other libraries in the ecosystem.41+42+## Migrations43+44+Upgrade guides between major versions.45+46+- [Migrating to v5](/reference/migrations/migrating-to-v5.md) — How to upgrade from Zustand v4.47+- [Migrating to v4](/reference/migrations/migrating-to-v4.md) — How to upgrade from Zustand v3.48+49+## Previous versions50+51+APIs that existed in older versions of Zustand and are no longer recommended for new code.52+53+- [createContext (v3)](/reference/previous-versions/zustand-v3-create-context.md) — The `createContext` export from `zustand/context`, deprecated in v4 and removed in v5.deleted:docs/bear.jpgbinary
A binary file, deleted.
deleted:docs/favicon.icobinary
A binary file, deleted.
added:docs/index.md+27 added
1+---2+pageType: home3+4+hero:5+ text: Bear necessities for React state6+ tagline: A tiny, predictable store with hooks-first ergonomics and escape hatches that stay out of your way.7+ actions:8+ - theme: brand9+ text: Introduction10+ link: /getting-started/introduction11+ - theme: alt12+ text: Quick Start13+ link: /learn/14+features:15+ - title: Minimal API, fast adoption16+ details: Create a store with a single hook, subscribe with selectors, and avoid boilerplate or providers.17+ - title: Safe under React concurrency18+ details: Built to avoid zombie children and tearing issues while keeping renders predictable.19+ - title: Works across React and vanilla20+ details: Share stores between React, React Native, and non-React environments with the same API surface.21+ - title: Batteries included22+ details: Opt into devtools, persistence, Redux-style middleware, and Immer without changing your mental model.23+ - title: TypeScript-first ergonomics24+ details: Strongly typed helpers and patterns so your state and actions stay inferred.25+ - title: Small footprint26+ details: Tiny bundle size with zero config and performance that keeps pace in production.27+---deleted:docs/llms.txt-51 removed
1-# Zustand2-3-Zustand is a fast, minimal state management library for React and JavaScript. It provides a simple API without context providers or boilerplate.4-5-## Docs6-7-- [Official Docs](https://zustand.docs.pmnd.rs): Complete reference for Zustand.8-- [Getting Started](https://zustand.docs.pmnd.rs/getting-started/introduction): Learn the basics and create your first store.9-10-## Core API11-12-- [createStore](https://zustand.docs.pmnd.rs/apis/create-store): Create a standalone store without React.13-- [shallow](https://zustand.docs.pmnd.rs/apis/shallow): Utility for shallow comparison of `objects`.14-15-## Middlewares16-17-- [combine](https://zustand.docs.pmnd.rs/middlewares/combine): Combine multiple slices into a single store.18-- [devtools](https://zustand.docs.pmnd.rs/middlewares/devtools): Debug state changes using Redux DevTools.19-- [immer](https://zustand.docs.pmnd.rs/middlewares/immer): Use `Immer` for immutable state updates.20-- [persist](https://zustand.docs.pmnd.rs/middlewares/persist): Persist state to `localStorage` or other storage engines.21-- [redux](https://zustand.docs.pmnd.rs/middlewares/redux): Use a reducer-style setup similar to `Redux`.22-- [subscribeWithSelector](https://zustand.docs.pmnd.rs/middlewares/subscribe-with-selector): Subscribe to specific slices with selector support.23-24-## React Bindings25-26-- [create](https://zustand.docs.pmnd.rs/apis/create): Bind a store to React for use with hooks.27-- [createWithEqualityFn](https://zustand.docs.pmnd.rs/apis/create-with-equality-fn): Like `create`, but allows custom equality functions.28-29-## React Hooks30-31-- [useStore](https://zustand.docs.pmnd.rs/hooks/use-store): Access and subscribe to store state.32-- [useStoreWithEqualityFn](https://zustand.docs.pmnd.rs/hooks/use-store-with-equality-fn): Same as `useStore`, but with custom equality checks.33-- [useShallow](https://zustand.docs.pmnd.rs/hooks/use-shallow): Use selectors with shallow equality comparison.34-35-## Migration Guides36-37-- [Migrate to v4](https://zustand.docs.pmnd.rs/migrations/migrating-to-v4): How to upgrade from Zustand v3.38-- [Migrate to v5](https://zustand.docs.pmnd.rs/migrations/migrating-to-v5): How to upgrade from Zustand v4.39-40-## Tutorials41-42-- [Tic-Tac-Toe Guide](https://zustand.docs.pmnd.rs/guides/tutorial-tic-tac-toe): Build a game using Zustand state.43-44-## More45-46-- [Third-party Libraries](https://zustand.docs.pmnd.rs/integrations/third-party-libraries): Integrations with third-party libraries.47-- [Zustand vs Other Libraries](https://zustand.docs.pmnd.rs/getting-started/comparison): Comparison with other state management libraries.48-- [TypeScript](https://zustand.docs.pmnd.rs/guides/typescript): Guide to using Zustand with TypeScript.49-- [Testing](https://zustand.docs.pmnd.rs/guides/testing): Best practices for testing Zustand stores.50-- [Next.js](https://zustand.docs.pmnd.rs/guides/nextjs): Using Zustand with Next.js for state management.51-- [Slices Pattern](https://zustand.docs.pmnd.rs/guides/slices-pattern): Organizing state into slices for scalability and maintainability.