create-with-equality-fn.md
This file
Path
docs/reference/apis/create-with-equality-fn.md
607 lines · 16.8 KiB · Markdown
Last changed by
docs(react): match createWithEqualityFn reference to source signature (#3491)Seydi Charyyevbefore adoption3fca846
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–16why, one step back1---2title: createWithEqualityFn3description: How to create efficient stores4tag: react5nav: 236---78`createWithEqualityFn` lets you create a React Hook with API utilities attached, just like `create`.9However, it offers a way to define a custom equality check. This allows for more granular control10over when components re-render, improving performance and responsiveness.1112> [!IMPORTANT]13> In order to use `createWithEqualityFn` from `zustand/traditional` you need to install14> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.1516```jsdocs(react): match createWithEqualityFn reference to source signature (#3491)Seydi Charyyevbefore adoption3fca846
line 17why, one step back17const useSomeStore = createWithEqualityFn(stateCreatorFn, defaultEqualityFn)Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 18–20why, one step back18```1920- [Types](#types)Hotfix section linking (#3410)Copilotbefore adoptionc49df38
line 21why, one step back21 - [Signature](#signature)Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 22–30why, one step back22- [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)Hotfix section linking (#3410)Copilotbefore adoptionc49df38
line 31why, one step back31 - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 32–37why, one step back3233## Types3435### Signature3637```tsdocs(react): match createWithEqualityFn reference to source signature (#3491)Seydi Charyyevbefore adoption3fca846
line 38why, one step back38createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, defaultEqualityFn?: <U>(a: U, b: U) => boolean): UseBoundStore<StoreApi<T>>Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 39–42why, one step back39```4041## Reference42docs(react): match createWithEqualityFn reference to source signature (#3491)Seydi Charyyevbefore adoption3fca846
line 43why, one step back43### `createWithEqualityFn(stateCreatorFn, defaultEqualityFn)`Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 44–48why, one step back4445#### Parameters4647- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.48 Usually, you will return an object with the methods you want to expose.docs(react): match createWithEqualityFn reference to source signature (#3491)Seydi Charyyevbefore adoption3fca846
line 49why, one step back49- **optional** `defaultEqualityFn`: Defaults to `Object.is`. A function that lets you skip re-renders.Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 50–607why, one step back5051#### Returns5253`createWithEqualityFn` returns a React Hook with API utilities attached, just like `create`. It54lets you return data that is based on current state, using a selector function, and lets you skip55re-renders using an equality function. It should take a selector function, and an equality function56as arguments.5758## Usage5960### Updating state based on previous state6162To update a state based on previous state we should use **updater functions**. Read more63about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).6465This example shows how you can support **updater functions** within **actions**.6667```tsx68import { createWithEqualityFn } from 'zustand/traditional'69import { shallow } from 'zustand/vanilla/shallow'7071type AgeStoreState = { age: number }7273type AgeStoreActions = {74 setAge: (75 nextAge:76 | AgeStoreState['age']77 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),78 ) => void79}8081type AgeStore = AgeStoreState & AgeStoreActions8283const useAgeStore = createWithEqualityFn<AgeStore>()(84 (set) => ({85 age: 42,86 setAge: (nextAge) =>87 set((state) => ({88 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,89 })),90 }),91 shallow,92)9394export default function App() {95 const age = useAgeStore((state) => state.age)96 const setAge = useAgeStore((state) => state.setAge)9798 function increment() {99 setAge((currentAge) => currentAge + 1)100 }101102 return (103 <>104 <h1>Your age: {age}</h1>105 <button106 type="button"107 onClick={() => {108 increment()109 increment()110 increment()111 }}112 >113 +3114 </button>115 <button116 type="button"117 onClick={() => {118 increment()119 }}120 >121 +1122 </button>123 </>124 )125}126```127128### Updating Primitives in State129130State can hold any kind of JavaScript value. When you want to update built-in primitive values like131numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied132correctly, and avoid unexpected behaviors.133134> [!NOTE]135> By default, `set` function performs a shallow merge. If you need to completely replace136> the state with a new one, use the `replace` parameter set to `true`137138```tsx139import { createWithEqualityFn } from 'zustand/traditional'140import { shallow } from 'zustand/vanilla/shallow'141142type XStore = number143144const useXStore = createWithEqualityFn<XStore>()(() => 0, shallow)145146export default function MovingDot() {147 const x = useXStore()148 const setX = (nextX: number) => {149 useXStore.setState(nextX, true)150 }151 const position = { y: 0, x }152153 return (154 <div155 onPointerMove={(e) => {156 setX(e.clientX)157 }}158 style={{159 position: 'relative',160 width: '100vw',161 height: '100vh',162 }}163 >164 <div165 style={{166 position: 'absolute',167 backgroundColor: 'red',168 borderRadius: '50%',169 transform: `translate(${position.x}px, ${position.y}px)`,170 left: -10,171 top: -10,172 width: 20,173 height: 20,174 }}175 />176 </div>177 )178}179```180181### Updating Objects in State182183Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store184them in state. Instead, when you want to update an object, you need to create a new one (or make a185copy of an existing one), and then set the state to use the new object.186187By default, `set` function performs a shallow merge. For most updates where you only need to modify188specific properties, the default shallow merge is preferred as it's more efficient. To completely189replace the state with a new one, use the `replace` parameter set to `true` with caution, as it190discards any existing nested data within the state.191192```tsx193import { createWithEqualityFn } from 'zustand/traditional'194import { shallow } from 'zustand/vanilla/shallow'195196type PositionStoreState = { position: { x: number; y: number } }197198type PositionStoreActions = {199 setPosition: (nextPosition: PositionStoreState['position']) => void200}201202type PositionStore = PositionStoreState & PositionStoreActions203204const usePositionStore = createWithEqualityFn<PositionStore>()(205 (set) => ({206 position: { x: 0, y: 0 },207 setPosition: (position) => set({ position }),208 }),209 shallow,210)211212export default function MovingDot() {213 const position = usePositionStore((state) => state.position)214 const setPosition = usePositionStore((state) => state.setPosition)215216 return (217 <div218 onPointerMove={(e) => {219 setPosition({220 x: e.clientX,221 y: e.clientY,222 })223 }}224 style={{225 position: 'relative',226 width: '100vw',227 height: '100vh',228 }}229 >230 <div231 style={{232 position: 'absolute',233 backgroundColor: 'red',234 borderRadius: '50%',235 transform: `translate(${position.x}px, ${position.y}px)`,236 left: -10,237 top: -10,238 width: 20,239 height: 20,240 }}241 />242 </div>243 )244}245```246247### Updating Arrays in State248249Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in250state. Just like with objects, when you want to update an array stored in state, you need to create251a new one (or make a copy of an existing one), and then set state to use the new array.252253By default, `set` function performs a shallow merge. To update array values we should assign new254values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely255replace the state with a new one, use the `replace` parameter set to `true`.256257> [!IMPORTANT]258> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,259> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid260> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,261> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.262263```tsx264import { createWithEqualityFn } from 'zustand/traditional'265import { shallow } from 'zustand/vanilla/shallow'266267type PositionStore = [number, number]268269const usePositionStore = createWithEqualityFn<PositionStore>()(270 () => [0, 0],271 shallow,272)273274export default function MovingDot() {275 const [x, y] = usePositionStore()276 const position = { x, y }277 const setPosition: typeof usePositionStore.setState = (nextPosition) => {278 usePositionStore.setState(nextPosition, true)279 }280281 return (282 <div283 onPointerMove={(e) => {284 setPosition([e.clientX, e.clientY])285 }}286 style={{287 position: 'relative',288 width: '100vw',289 height: '100vh',290 }}291 >292 <div293 style={{294 position: 'absolute',295 backgroundColor: 'red',296 borderRadius: '50%',297 transform: `translate(${position.x}px, ${position.y}px)`,298 left: -10,299 top: -10,300 width: 20,301 height: 20,302 }}303 />304 </div>305 )306}307```308309### Updating state with no store actions310311Defining actions at module level, external to the store have a few advantages like: it doesn't312require a hook to call an action, and it facilitates code splitting.313314> [!NOTE]315> The recommended way is to colocate actions and states within the store (let your actions be316> located together with your state).317318```tsx319import { createWithEqualityFn } from 'zustand/traditional'320import { shallow } from 'zustand/vanilla/shallow'321322const usePositionStore = createWithEqualityFn<{323 x: number324 y: number325}>()(() => ({ x: 0, y: 0 }), shallow)326327const setPosition: typeof usePositionStore.setState = (nextPosition) => {328 usePositionStore.setState(nextPosition)329}330331export default function MovingDot() {332 const position = usePositionStore()333334 return (335 <div336 style={{337 position: 'relative',338 width: '100vw',339 height: '100vh',340 }}341 >342 <div343 style={{344 position: 'absolute',345 backgroundColor: 'red',346 borderRadius: '50%',347 transform: `translate(${position.x}px, ${position.y}px)`,348 left: -10,349 top: -10,350 width: 20,351 height: 20,352 }}353 onMouseEnter={(event) => {354 const parent = event.currentTarget.parentElement355 const parentWidth = parent.clientWidth356 const parentHeight = parent.clientHeight357358 setPosition({359 x: Math.ceil(Math.random() * parentWidth),360 y: Math.ceil(Math.random() * parentHeight),361 })362 }}363 />364 </div>365 )366}367```368369### Subscribing to state updates370371By subscribing to state updates, you register a callback that fires whenever the store's state372updates. We can use `subscribe` for external state management.373374```tsx375import { useEffect } from 'react'376import { createWithEqualityFn } from 'zustand/traditional'377import { shallow } from 'zustand/vanilla/shallow'378379type PositionStoreState = { position: { x: number; y: number } }380381type PositionStoreActions = {382 setPosition: (nextPosition: PositionStoreState['position']) => void383}384385type PositionStore = PositionStoreState & PositionStoreActions386387const usePositionStore = createWithEqualityFn<PositionStore>()(388 (set) => ({389 position: { x: 0, y: 0 },390 setPosition: (nextPosition) => set({ position: nextPosition }),391 }),392 shallow,393)394395export default function MovingDot() {396 const position = usePositionStore((state) => state.position)397 const setPosition = usePositionStore((state) => state.setPosition)398399 useEffect(() => {400 const unsubscribePositionStore = usePositionStore.subscribe(401 ({ position }) => {402 console.log('new position', { position })403 },404 )405406 return () => {407 unsubscribePositionStore()408 }409 }, [])410411 return (412 <div413 style={{414 position: 'relative',415 width: '100vw',416 height: '100vh',417 }}418 >419 <div420 style={{421 position: 'absolute',422 backgroundColor: 'red',423 borderRadius: '50%',424 transform: `translate(${position.x}px, ${position.y}px)`,425 left: -10,426 top: -10,427 width: 20,428 height: 20,429 }}430 onMouseEnter={(event) => {431 const parent = event.currentTarget.parentElement432 const parentWidth = parent.clientWidth433 const parentHeight = parent.clientHeight434435 setPosition({436 x: Math.ceil(Math.random() * parentWidth),437 y: Math.ceil(Math.random() * parentHeight),438 })439 }}440 />441 </div>442 )443}444```445446## Troubleshooting447448### I’ve updated the state, but the screen doesn’t update449450In the previous example, the `position` object is always created fresh from the current cursor451position. But often, you will want to include existing data as a part of the new object you’re452creating. For example, you may want to update only one field in a form, but keep the previous453values for all other fields.454455These input fields don’t work because the `onChange` handlers mutate the state:456457```tsx458import { createWithEqualityFn } from 'zustand/traditional'459import { shallow } from 'zustand/vanilla/shallow'460461type PersonStoreState = {462 person: { firstName: string; lastName: string; email: string }463}464465type PersonStoreActions = {466 setPerson: (nextPerson: PersonStoreState['person']) => void467}468469type PersonStore = PersonStoreState & PersonStoreActions470471const usePersonStore = createWithEqualityFn<PersonStore>()(472 (set) => ({473 person: {474 firstName: 'Barbara',475 lastName: 'Hepworth',476 email: 'bhepworth@sculpture.com',477 },478 setPerson: (person) => set({ person }),479 }),480 shallow,481)482483export default function Form() {484 const person = usePersonStore((state) => state.person)485 const setPerson = usePersonStore((state) => state.setPerson)486487 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {488 person.firstName = e.target.value489 }490491 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {492 person.lastName = e.target.value493 }494495 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {496 person.email = e.target.value497 }498499 return (500 <>501 <label style={{ display: 'block' }}>502 First name:503 <input value={person.firstName} onChange={handleFirstNameChange} />504 </label>505 <label style={{ display: 'block' }}>506 Last name:507 <input value={person.lastName} onChange={handleLastNameChange} />508 </label>509 <label style={{ display: 'block' }}>510 Email:511 <input value={person.email} onChange={handleEmailChange} />512 </label>513 <p>514 {person.firstName} {person.lastName} ({person.email})515 </p>516 </>517 )518}519```520521For example, this line mutates the state from a past render:522523```tsx524person.firstName = e.target.value525```526527The reliable way to get the behavior you’re looking for is to create a new object and pass it to528`setPerson`. But here you want to also copy the existing data into it because only one of the529fields has changed:530531```ts532setPerson({ ...person, firstName: e.target.value }) // New first name from the input533```534535> [!NOTE]536> We don’t need to copy every property separately due to `set` function performing shallow merge by537> default.538539Now the form works!540541Notice how you didn’t declare a separate state variable for each input field. For large forms,542keeping all data grouped in an object is very convenient—as long as you update it correctly!543544```tsx {32,36,40}545import { type ChangeEvent } from 'react'546import { createWithEqualityFn } from 'zustand/traditional'547import { shallow } from 'zustand/vanilla/shallow'548549type PersonStoreState = {550 person: { firstName: string; lastName: string; email: string }551}552553type PersonStoreActions = {554 setPerson: (nextPerson: PersonStoreState['person']) => void555}556557type PersonStore = PersonStoreState & PersonStoreActions558559const usePersonStore = createWithEqualityFn<PersonStore>()(560 (set) => ({561 person: {562 firstName: 'Barbara',563 lastName: 'Hepworth',564 email: 'bhepworth@sculpture.com',565 },566 setPerson: (nextPerson) => set({ person: nextPerson }),567 }),568 shallow,569)570571export default function Form() {572 const person = usePersonStore((state) => state.person)573 const setPerson = usePersonStore((state) => state.setPerson)574575 function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {576 setPerson({ ...person, firstName: e.target.value })577 }578579 function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {580 setPerson({ ...person, lastName: e.target.value })581 }582583 function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {584 setPerson({ ...person, email: e.target.value })585 }586587 return (588 <>589 <label style={{ display: 'block' }}>590 First name:591 <input value={person.firstName} onChange={handleFirstNameChange} />592 </label>593 <label style={{ display: 'block' }}>594 Last name:595 <input value={person.lastName} onChange={handleLastNameChange} />596 </label>597 <label style={{ display: 'block' }}>598 Email:599 <input value={person.email} onChange={handleEmailChange} />600 </label>601 <p>602 {person.firstName} {person.lastName} ({person.email})603 </p>604 </>605 )606}607```