use-store-with-equality-fn.md
This file
Path
docs/reference/hooks/use-store-with-equality-fn.md
959 lines · 23.2 KiB · Markdown
Last changed by
docs(react): fix equalityFn type in useStoreWithEqualityFn signature (#3489)Seydi Charyyevbefore adoption3edacae
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–25why, one step back1---2title: useStoreWithEqualityFn3description: How to use vanilla stores effectively in React4tag: react5nav: 266---78`useStoreWithEqualityFn` is a React Hook that lets you use a vanilla store in React, just like9`useStore`. However, it offers a way to define a custom equality check. This allows for more10granular control over when components re-render, improving performance and responsiveness.1112> [!IMPORTANT]13> In order to use `useStoreWithEqualityFn` from `zustand/traditional` you need to install14> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.1516```js17const someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)18```1920- [Types](#types)21 - [Signature](#signature)22- [Reference](#reference)23- [Usage](#usage)24 - [Using a global vanilla store in React](#using-a-global-vanilla-store-in-react)25 - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)Hotfix section linking (#3410)Copilotbefore adoptionc49df38
lines 26–27why, one step back26 - [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>)Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
line 28why, one step back28- [Troubleshooting](#troubleshooting)Hotfix section linking (#3410)Copilotbefore adoptionc49df38
lines 29–30why, one step back2930## TypesRevamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 31–34why, one step back3132### Signature3334```tsdocs(react): fix equalityFn type in useStoreWithEqualityFn signature (#3489)Seydi Charyyevbefore adoption3edacae
line 35why, one step back35useStoreWithEqualityFn<T, U = T>(store: StoreApi<T>, selectorFn: (state: T) => U, equalityFn?: (a: U, b: U) => boolean): URevamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 36–959why, one step back36```3738## Reference3940### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`4142#### Parameters4344- `storeApi`: The instance that lets you access to store API utilities.45- `selectorFn`: A function that lets you return data that is based on current state.46- `equalityFn`: A function that lets you skip re-renders.4748#### Returns4950`useStoreWithEqualityFn` returns any data based on current state depending on the selector function,51and lets you skip re-renders using an equality function. It should take a store, a selector52function, and an equality function as arguments.5354## Usage5556### Using a global vanilla store in React5758First, let's set up a store that will hold the position of the dot on the screen. We'll define the59store to manage `x` and `y` coordinates and provide an action to update these coordinates.6061```tsx62import { createStore, useStore } from 'zustand'6364type PositionStoreState = { position: { x: number; y: number } }6566type PositionStoreActions = {67 setPosition: (nextPosition: PositionStoreState['position']) => void68}6970type PositionStore = PositionStoreState & PositionStoreActions7172const positionStore = createStore<PositionStore>()((set) => ({73 position: { x: 0, y: 0 },74 setPosition: (position) => set({ position }),75}))76```7778Next, we'll create a `MovingDot` component that renders a div representing the dot. This component79will use the store to track and update the dot's position.8081```tsx82function MovingDot() {83 const position = useStoreWithEqualityFn(84 positionStore,85 (state) => state.position,86 shallow,87 )88 const setPosition = useStoreWithEqualityFn(89 positionStore,90 (state) => state.setPosition,91 shallow,92 )9394 return (95 <div96 onPointerMove={(e) => {97 setPosition({98 x: e.clientX,99 y: e.clientY,100 })101 }}102 style={{103 position: 'relative',104 width: '100vw',105 height: '100vh',106 }}107 >108 <div109 style={{110 position: 'absolute',111 backgroundColor: 'red',112 borderRadius: '50%',113 transform: `translate(${position.x}px, ${position.y}px)`,114 left: -10,115 top: -10,116 width: 20,117 height: 20,118 }}119 />120 </div>121 )122}123```124125Finally, we’ll render the `MovingDot` component in our `App` component.126127```tsx128export default function App() {129 return <MovingDot />130}131```132133Here is what the code should look like:134135```tsx136import { createStore } from 'zustand'137import { useStoreWithEqualityFn } from 'zustand/traditional'138import { shallow } from 'zustand/shallow'139140type PositionStoreState = { position: { x: number; y: number } }141142type PositionStoreActions = {143 setPosition: (nextPosition: PositionStoreState['position']) => void144}145146type PositionStore = PositionStoreState & PositionStoreActions147148const positionStore = createStore<PositionStore>()((set) => ({149 position: { x: 0, y: 0 },150 setPosition: (position) => set({ position }),151}))152153function MovingDot() {154 const position = useStoreWithEqualityFn(155 positionStore,156 (state) => state.position,157 shallow,158 )159 const setPosition = useStoreWithEqualityFn(160 positionStore,161 (state) => state.setPosition,162 shallow,163 )164165 return (166 <div167 onPointerMove={(e) => {168 setPosition({169 x: e.clientX,170 y: e.clientY,171 })172 }}173 style={{174 position: 'relative',175 width: '100vw',176 height: '100vh',177 }}178 >179 <div180 style={{181 position: 'absolute',182 backgroundColor: 'red',183 borderRadius: '50%',184 transform: `translate(${position.x}px, ${position.y}px)`,185 left: -10,186 top: -10,187 width: 20,188 height: 20,189 }}190 />191 </div>192 )193}194195export default function App() {196 return <MovingDot />197}198```199200### Using dynamic global vanilla stores in React201202First, we'll create a factory function that generates a store for managing the counter state.203Each tab will have its own instance of this store.204205```ts206import { createStore } from 'zustand'207208type CounterState = {209 count: number210}211212type CounterActions = { increment: () => void }213214type CounterStore = CounterState & CounterActions215216const createCounterStore = () => {217 return createStore<CounterStore>()((set) => ({218 count: 0,219 increment: () => {220 set((state) => ({ count: state.count + 1 }))221 },222 }))223}224```225226Next, we'll create a factory function that manages the creation and retrieval of counter stores.227This allows each tab to have its own independent counter.228229```ts230const defaultCounterStores = new Map<231 string,232 ReturnType<typeof createCounterStore>233>()234235const createCounterStoreFactory = (236 counterStores: typeof defaultCounterStores,237) => {238 return (counterStoreKey: string) => {239 if (!counterStores.has(counterStoreKey)) {240 counterStores.set(counterStoreKey, createCounterStore())241 }242 return counterStores.get(counterStoreKey)!243 }244}245246const getOrCreateCounterStoreByKey =247 createCounterStoreFactory(defaultCounterStores)248```249250Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s251counter.252253```tsx254const [currentTabIndex, setCurrentTabIndex] = useState(0)255const counterState = useStoreWithEqualityFn(256 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),257 (state) => state,258 shallow,259)260261return (262 <div style={{ fontFamily: 'monospace' }}>263 <div264 style={{265 display: 'flex',266 gap: '0.5rem',267 borderBottom: '1px solid salmon',268 paddingBottom: 4,269 }}270 >271 <button272 type="button"273 style={{274 border: '1px solid salmon',275 backgroundColor: '#fff',276 cursor: 'pointer',277 }}278 onClick={() => setCurrentTabIndex(0)}279 >280 Tab 1281 </button>282 <button283 type="button"284 style={{285 border: '1px solid salmon',286 backgroundColor: '#fff',287 cursor: 'pointer',288 }}289 onClick={() => setCurrentTabIndex(1)}290 >291 Tab 2292 </button>293 <button294 type="button"295 style={{296 border: '1px solid salmon',297 backgroundColor: '#fff',298 cursor: 'pointer',299 }}300 onClick={() => setCurrentTabIndex(2)}301 >302 Tab 3303 </button>304 </div>305 <div style={{ padding: 4 }}>306 Content of Tab {currentTabIndex + 1}307 <br /> <br />308 <button type="button" onClick={() => counterState.increment()}>309 Count: {counterState.count}310 </button>311 </div>312 </div>313)314```315316Finally, we'll create the `App` component, which renders the tabs and their respective counters.317The counter state is managed independently for each tab.318319```tsx320export default function App() {321 return <Tabs />322}323```324325Here is what the code should look like:326327```tsx328import { useState } from 'react'329import { createStore } from 'zustand'330import { useStoreWithEqualityFn } from 'zustand/traditional'331import { shallow } from 'zustand/shallow'332333type CounterState = {334 count: number335}336337type CounterActions = { increment: () => void }338339type CounterStore = CounterState & CounterActions340341const createCounterStore = () => {342 return createStore<CounterStore>()((set) => ({343 count: 0,344 increment: () => {345 set((state) => ({ count: state.count + 1 }))346 },347 }))348}349350const defaultCounterStores = new Map<351 string,352 ReturnType<typeof createCounterStore>353>()354355const createCounterStoreFactory = (356 counterStores: typeof defaultCounterStores,357) => {358 return (counterStoreKey: string) => {359 if (!counterStores.has(counterStoreKey)) {360 counterStores.set(counterStoreKey, createCounterStore())361 }362 return counterStores.get(counterStoreKey)!363 }364}365366const getOrCreateCounterStoreByKey =367 createCounterStoreFactory(defaultCounterStores)368369export default function App() {370 const [currentTabIndex, setCurrentTabIndex] = useState(0)371 const counterState = useStoreWithEqualityFn(372 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),373 (state) => state,374 shallow,375 )376377 return (378 <div style={{ fontFamily: 'monospace' }}>379 <div380 style={{381 display: 'flex',382 gap: '0.5rem',383 borderBottom: '1px solid salmon',384 paddingBottom: 4,385 }}386 >387 <button388 type="button"389 style={{390 border: '1px solid salmon',391 backgroundColor: '#fff',392 cursor: 'pointer',393 }}394 onClick={() => setCurrentTabIndex(0)}395 >396 Tab 1397 </button>398 <button399 type="button"400 style={{401 border: '1px solid salmon',402 backgroundColor: '#fff',403 cursor: 'pointer',404 }}405 onClick={() => setCurrentTabIndex(1)}406 >407 Tab 2408 </button>409 <button410 type="button"411 style={{412 border: '1px solid salmon',413 backgroundColor: '#fff',414 cursor: 'pointer',415 }}416 onClick={() => setCurrentTabIndex(2)}417 >418 Tab 3419 </button>420 </div>421 <div style={{ padding: 4 }}>422 Content of Tab {currentTabIndex + 1}423 <br /> <br />424 <button type="button" onClick={() => counterState.increment()}>425 Count: {counterState.count}426 </button>427 </div>428 </div>429 )430}431```432433### Using scoped (non-global) vanilla store in React434435First, let's set up a store that will hold the position of the dot on the screen. We'll define the436store to manage `x` and `y` coordinates and provide an action to update these coordinates.437438```tsx439type PositionStoreState = { position: { x: number; y: number } }440441type PositionStoreActions = {442 setPosition: (nextPosition: PositionStoreState['position']) => void443}444445type PositionStore = PositionStoreState & PositionStoreActions446447const createPositionStore = () => {448 return createStore<PositionStore>()((set) => ({449 position: { x: 0, y: 0 },450 setPosition: (position) => set({ position }),451 }))452}453```454455Next, we'll create a context and a provider component to pass down the store through the React456component tree. This allows each `MovingDot` component to have its own independent state.457458```tsx459const PositionStoreContext = createContext<ReturnType<460 typeof createPositionStore461> | null>(null)462463function PositionStoreProvider({ children }: { children: ReactNode }) {464 const [store] = useState(() => createPositionStore())465 return (466 <PositionStoreContext.Provider value={store}>467 {children}468 </PositionStoreContext.Provider>469 )470}471```472473To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook474will read the store from the context and allow us to select specific parts of the state.475476```ts477function usePositionStore<U>(selector: (state: PositionStore) => U) {478 const store = useContext(PositionStoreContext)479480 if (store === null) {481 throw new Error(482 'usePositionStore must be used within PositionStoreProvider',483 )484 }485486 return useStoreWithEqualityFn(store, selector, shallow)487}488```489490Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor491within its container.492493```tsx494function MovingDot({ color }: { color: string }) {495 const position = usePositionStore((state) => state.position)496 const setPosition = usePositionStore((state) => state.setPosition)497498 return (499 <div500 onPointerMove={(e) => {501 setPosition({502 x:503 e.clientX > e.currentTarget.clientWidth504 ? e.clientX - e.currentTarget.clientWidth505 : e.clientX,506 y: e.clientY,507 })508 }}509 style={{510 position: 'relative',511 width: '50vw',512 height: '100vh',513 }}514 >515 <div516 style={{517 position: 'absolute',518 backgroundColor: color,519 borderRadius: '50%',520 transform: `translate(${position.x}px, ${position.y}px)`,521 left: -10,522 top: -10,523 width: 20,524 height: 20,525 }}526 />527 </div>528 )529}530```531532Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`533components, each with its own independent state.534535```tsx536export default function App() {537 return (538 <div style={{ display: 'flex' }}>539 <PositionStoreProvider>540 <MovingDot color="red" />541 </PositionStoreProvider>542 <PositionStoreProvider>543 <MovingDot color="blue" />544 </PositionStoreProvider>545 </div>546 )547}548```549550Here is what the code should look like:551552```tsx553import { type ReactNode, useState, createContext, useContext } from 'react'554import { createStore } from 'zustand'555import { useStoreWithEqualityFn } from 'zustand/traditional'556import { shallow } from 'zustand/shallow'557558type PositionStoreState = { position: { x: number; y: number } }559560type PositionStoreActions = {561 setPosition: (nextPosition: PositionStoreState['position']) => void562}563564type PositionStore = PositionStoreState & PositionStoreActions565566const createPositionStore = () => {567 return createStore<PositionStore>()((set) => ({568 position: { x: 0, y: 0 },569 setPosition: (position) => set({ position }),570 }))571}572573const PositionStoreContext = createContext<ReturnType<574 typeof createPositionStore575> | null>(null)576577function PositionStoreProvider({ children }: { children: ReactNode }) {578 const [store] = useState(() => createPositionStore())579 return (580 <PositionStoreContext.Provider value={store}>581 {children}582 </PositionStoreContext.Provider>583 )584}585586function usePositionStore<U>(selector: (state: PositionStore) => U) {587 const store = useContext(PositionStoreContext)588589 if (store === null) {590 throw new Error(591 'usePositionStore must be used within PositionStoreProvider',592 )593 }594595 return useStoreWithEqualityFn(store, selector, shallow)596}597598function MovingDot({ color }: { color: string }) {599 const position = usePositionStore((state) => state.position)600 const setPosition = usePositionStore((state) => state.setPosition)601602 return (603 <div604 onPointerMove={(e) => {605 setPosition({606 x:607 e.clientX > e.currentTarget.clientWidth608 ? e.clientX - e.currentTarget.clientWidth609 : e.clientX,610 y: e.clientY,611 })612 }}613 style={{614 position: 'relative',615 width: '50vw',616 height: '100vh',617 }}618 >619 <div620 style={{621 position: 'absolute',622 backgroundColor: color,623 borderRadius: '50%',624 transform: `translate(${position.x}px, ${position.y}px)`,625 left: -10,626 top: -10,627 width: 20,628 height: 20,629 }}630 />631 </div>632 )633}634635export default function App() {636 return (637 <div style={{ display: 'flex' }}>638 <PositionStoreProvider>639 <MovingDot color="red" />640 </PositionStoreProvider>641 <PositionStoreProvider>642 <MovingDot color="blue" />643 </PositionStoreProvider>644 </div>645 )646}647```648649### Using dynamic scoped (non-global) vanilla stores in React650651First, we'll create a factory function that generates a store for managing the counter state.652Each tab will have its own instance of this store.653654```ts655type CounterState = {656 count: number657}658659type CounterActions = { increment: () => void }660661type CounterStore = CounterState & CounterActions662663const createCounterStore = () => {664 return createStore<CounterStore>()((set) => ({665 count: 0,666 increment: () => {667 set((state) => ({ count: state.count + 1 }))668 },669 }))670}671```672673Next, we'll create a factory function that manages the creation and retrieval of counter stores.674This allows each tab to have its own independent counter.675676```ts677const createCounterStoreFactory = (678 counterStores: Map<string, ReturnType<typeof createCounterStore>>,679) => {680 return (counterStoreKey: string) => {681 if (!counterStores.has(counterStoreKey)) {682 counterStores.set(counterStoreKey, createCounterStore())683 }684 return counterStores.get(counterStoreKey)!685 }686}687```688689Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context690for this.691692```tsx693const CounterStoresContext = createContext(null)694695const CounterStoresProvider = ({ children }) => {696 const [stores] = useState(697 () => new Map<string, ReturnType<typeof createCounterStore>>(),698 )699700 return (701 <CounterStoresContext.Provider value={stores}>702 {children}703 </CounterStoresContext.Provider>704 )705}706```707708Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a709given tab.710711```tsx712const useCounterStore = <U,>(713 key: string,714 selector: (state: CounterStore) => U,715) => {716 const stores = useContext(CounterStoresContext)717718 if (stores === undefined) {719 throw new Error('useCounterStore must be used within CounterStoresProvider')720 }721722 const getOrCreateCounterStoreByKey = useCallback(723 (key: string) => createCounterStoreFactory(stores!)(key),724 [stores],725 )726727 return useStore(getOrCreateCounterStoreByKey(key), selector)728}729```730731Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s732counter.733734```tsx735function Tabs() {736 const [currentTabIndex, setCurrentTabIndex] = useState(0)737 const counterState = useCounterStore(738 `tab-${currentTabIndex}`,739 (state) => state,740 )741742 return (743 <div style={{ fontFamily: 'monospace' }}>744 <div745 style={{746 display: 'flex',747 gap: '0.5rem',748 borderBottom: '1px solid salmon',749 paddingBottom: 4,750 }}751 >752 <button753 type="button"754 style={{755 border: '1px solid salmon',756 backgroundColor: '#fff',757 cursor: 'pointer',758 }}759 onClick={() => setCurrentTabIndex(0)}760 >761 Tab 1762 </button>763 <button764 type="button"765 style={{766 border: '1px solid salmon',767 backgroundColor: '#fff',768 cursor: 'pointer',769 }}770 onClick={() => setCurrentTabIndex(1)}771 >772 Tab 2773 </button>774 <button775 type="button"776 style={{777 border: '1px solid salmon',778 backgroundColor: '#fff',779 cursor: 'pointer',780 }}781 onClick={() => setCurrentTabIndex(2)}782 >783 Tab 3784 </button>785 </div>786 <div style={{ padding: 4 }}>787 Content of Tab {currentTabIndex + 1}788 <br /> <br />789 <button type="button" onClick={() => counterState.increment()}>790 Count: {counterState.count}791 </button>792 </div>793 </div>794 )795}796```797798Finally, we'll create the `App` component, which renders the tabs and their respective counters.799The counter state is managed independently for each tab.800801```tsx802export default function App() {803 return (804 <CounterStoresProvider>805 <Tabs />806 </CounterStoresProvider>807 )808}809```810811Here is what the code should look like:812813```tsx814import {815 type ReactNode,816 useState,817 useCallback,818 useContext,819 createContext,820} from 'react'821import { createStore, useStore } from 'zustand'822823type CounterState = {824 count: number825}826827type CounterActions = { increment: () => void }828829type CounterStore = CounterState & CounterActions830831const createCounterStore = () => {832 return createStore<CounterStore>()((set) => ({833 count: 0,834 increment: () => {835 set((state) => ({ count: state.count + 1 }))836 },837 }))838}839840const createCounterStoreFactory = (841 counterStores: Map<string, ReturnType<typeof createCounterStore>>,842) => {843 return (counterStoreKey: string) => {844 if (!counterStores.has(counterStoreKey)) {845 counterStores.set(counterStoreKey, createCounterStore())846 }847 return counterStores.get(counterStoreKey)!848 }849}850851const CounterStoresContext = createContext<Map<852 string,853 ReturnType<typeof createCounterStore>854> | null>(null)855856const CounterStoresProvider = ({ children }: { children: ReactNode }) => {857 const [stores] = useState(858 () => new Map<string, ReturnType<typeof createCounterStore>>(),859 )860861 return (862 <CounterStoresContext.Provider value={stores}>863 {children}864 </CounterStoresContext.Provider>865 )866}867868const useCounterStore = <U,>(869 key: string,870 selector: (state: CounterStore) => U,871) => {872 const stores = useContext(CounterStoresContext)873874 if (stores === undefined) {875 throw new Error('useCounterStore must be used within CounterStoresProvider')876 }877878 const getOrCreateCounterStoreByKey = useCallback(879 (key: string) => createCounterStoreFactory(stores!)(key),880 [stores],881 )882883 return useStore(getOrCreateCounterStoreByKey(key), selector)884}885886function Tabs() {887 const [currentTabIndex, setCurrentTabIndex] = useState(0)888 const counterState = useCounterStore(889 `tab-${currentTabIndex}`,890 (state) => state,891 )892893 return (894 <div style={{ fontFamily: 'monospace' }}>895 <div896 style={{897 display: 'flex',898 gap: '0.5rem',899 borderBottom: '1px solid salmon',900 paddingBottom: 4,901 }}902 >903 <button904 type="button"905 style={{906 border: '1px solid salmon',907 backgroundColor: '#fff',908 cursor: 'pointer',909 }}910 onClick={() => setCurrentTabIndex(0)}911 >912 Tab 1913 </button>914 <button915 type="button"916 style={{917 border: '1px solid salmon',918 backgroundColor: '#fff',919 cursor: 'pointer',920 }}921 onClick={() => setCurrentTabIndex(1)}922 >923 Tab 2924 </button>925 <button926 type="button"927 style={{928 border: '1px solid salmon',929 backgroundColor: '#fff',930 cursor: 'pointer',931 }}932 onClick={() => setCurrentTabIndex(2)}933 >934 Tab 3935 </button>936 </div>937 <div style={{ padding: 4 }}>938 Content of Tab {currentTabIndex + 1}939 <br /> <br />940 <button type="button" onClick={() => counterState.increment()}>941 Count: {counterState.count}942 </button>943 </div>944 </div>945 )946}947948export default function App() {949 return (950 <CounterStoresProvider>951 <Tabs />952 </CounterStoresProvider>953 )954}955```956957## Troubleshooting958959TBD