use-store.md
This file
Path
docs/reference/hooks/use-store.md
923 lines · 21.9 KiB · Markdown
Last changed by
docs(react): fix useStore signature in reference docs (#3487)Seydi Charyyevbefore adoption7134647
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–17why, one step back1---2title: useStore3description: How to use vanilla stores in React4tag: react5nav: 256---78`useStore` is a React Hook that lets you use a vanilla store in React.910```js11const someState = useStore(store, selectorFn)12```1314- [Types](#types)15 - [Signature](#signature)16- [Reference](#reference)17- [Usage](#usage)Hotfix section linking (#3410)Copilotbefore adoptionc49df38
line 18why, one step back18 - [Use a vanilla store in React](#using-a-global-vanilla-store-in-react)Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
line 19why, one step back19 - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)Hotfix section linking (#3410)Copilotbefore adoptionc49df38
lines 20–21why, one step back20 - [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>)Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 22–28why, one step back22- [Troubleshooting](#troubleshooting)2324## Types2526### Signature2728```tsdocs(react): fix useStore signature in reference docs (#3487)Seydi Charyyevbefore adoption7134647
line 29why, one step back29useStore<T, U = T>(store: StoreApi<T>, selectorFn?: (state: T) => U): URevamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 30–923why, one step back30```3132## Reference3334### `useStore(store, selectorFn)`3536#### Parameters3738- `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.4041#### Returns4243`useStore` returns any data based on current state depending on the selector function. It should44take a store, and a selector function as arguments.4546## Usage4748### Using a global vanilla store in React4950First, let's set up a store that will hold the position of the dot on the screen. We'll define the51store to manage `x` and `y` coordinates and provide an action to update these coordinates.5253```tsx54type PositionStoreState = { position: { x: number; y: number } }5556type PositionStoreActions = {57 setPosition: (nextPosition: PositionStoreState['position']) => void58}5960type PositionStore = PositionStoreState & PositionStoreActions6162const positionStore = createStore<PositionStore>()((set) => ({63 position: { x: 0, y: 0 },64 setPosition: (position) => set({ position }),65}))66```6768Next, we'll create a `MovingDot` component that renders a div representing the dot. This component69will use the store to track and update the dot's position.7071```tsx72function MovingDot() {73 const position = useStore(positionStore, (state) => state.position)74 const setPosition = useStore(positionStore, (state) => state.setPosition)7576 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```106107Finally, we’ll render the `MovingDot` component in our `App` component.108109```tsx110export default function App() {111 return <MovingDot />112}113```114115Here is what the code should look like:116117```tsx118import { createStore, useStore } from 'zustand'119120type PositionStoreState = { position: { x: number; y: number } }121122type PositionStoreActions = {123 setPosition: (nextPosition: PositionStoreState['position']) => void124}125126type PositionStore = PositionStoreState & PositionStoreActions127128const positionStore = createStore<PositionStore>()((set) => ({129 position: { x: 0, y: 0 },130 setPosition: (position) => set({ position }),131}))132133function MovingDot() {134 const position = useStore(positionStore, (state) => state.position)135 const setPosition = useStore(positionStore, (state) => state.setPosition)136137 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}166167export default function App() {168 return <MovingDot />169}170```171172### Using dynamic global vanilla stores in React173174First, we'll create a factory function that generates a store for managing the counter state.175Each tab will have its own instance of this store.176177```ts178type CounterState = {179 count: number180}181182type CounterActions = { increment: () => void }183184type CounterStore = CounterState & CounterActions185186const createCounterStore = () => {187 return createStore<CounterStore>()((set) => ({188 count: 0,189 increment: () => {190 set((state) => ({ count: state.count + 1 }))191 },192 }))193}194```195196Next, we'll create a factory function that manages the creation and retrieval of counter stores.197This allows each tab to have its own independent counter.198199```ts200const defaultCounterStores = new Map<201 string,202 ReturnType<typeof createCounterStore>203>()204205const 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}215216const getOrCreateCounterStoreByKey =217 createCounterStoreFactory(defaultCounterStores)218```219220Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s221counter.222223```tsx224const [currentTabIndex, setCurrentTabIndex] = useState(0)225const counterState = useStore(226 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),227)228229return (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```283284Finally, we'll create the `App` component, which renders the tabs and their respective counters.285The counter state is managed independently for each tab.286287```tsx288export default function App() {289 return <Tabs />290}291```292293Here is what the code should look like:294295```tsx296import { useState } from 'react'297import { createStore, useStore } from 'zustand'298299type CounterState = {300 count: number301}302303type CounterActions = { increment: () => void }304305type CounterStore = CounterState & CounterActions306307const createCounterStore = () => {308 return createStore<CounterStore>()((set) => ({309 count: 0,310 increment: () => {311 set((state) => ({ count: state.count + 1 }))312 },313 }))314}315316const defaultCounterStores = new Map<317 string,318 ReturnType<typeof createCounterStore>319>()320321const 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}331332const getOrCreateCounterStoreByKey =333 createCounterStoreFactory(defaultCounterStores)334335export default function App() {336 const [currentTabIndex, setCurrentTabIndex] = useState(0)337 const counterState = useStore(338 getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),339 )340341 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```396397### Using scoped (non-global) vanilla store in React398399First, let's set up a store that will hold the position of the dot on the screen. We'll define the400store to manage `x` and `y` coordinates and provide an action to update these coordinates.401402```tsx403type PositionStoreState = { position: { x: number; y: number } }404405type PositionStoreActions = {406 setPosition: (nextPosition: PositionStoreState['position']) => void407}408409type PositionStore = PositionStoreState & PositionStoreActions410411const createPositionStore = () => {412 return createStore<PositionStore>()((set) => ({413 position: { x: 0, y: 0 },414 setPosition: (position) => set({ position }),415 }))416}417```418419Next, we'll create a context and a provider component to pass down the store through the React420component tree. This allows each `MovingDot` component to have its own independent state.421422```tsx423const PositionStoreContext = createContext<ReturnType<424 typeof createPositionStore425> | null>(null)426427function PositionStoreProvider({ children }: { children: ReactNode }) {428 const [store] = useState(() => createPositionStore())429 return (430 <PositionStoreContext.Provider value={store}>431 {children}432 </PositionStoreContext.Provider>433 )434}435```436437To simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook438will read the store from the context and allow us to select specific parts of the state.439440```ts441function usePositionStore<U>(selector: (state: PositionStore) => U) {442 const store = useContext(PositionStoreContext)443444 if (store === null) {445 throw new Error(446 'usePositionStore must be used within PositionStoreProvider',447 )448 }449450 return useStore(store, selector)451}452```453454Now, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor455within its container.456457```tsx458function MovingDot({ color }: { color: string }) {459 const position = usePositionStore((state) => state.position)460 const setPosition = usePositionStore((state) => state.setPosition)461462 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```495496Finally, we'll bring everything together in the `App` component, where we render two `MovingDot`497components, each with its own independent state.498499```tsx500export 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```513514Here is what the code should look like:515516```tsx517import { type ReactNode, useState, createContext, useContext } from 'react'518import { createStore, useStore } from 'zustand'519520type PositionStoreState = { position: { x: number; y: number } }521522type PositionStoreActions = {523 setPosition: (nextPosition: PositionStoreState['position']) => void524}525526type PositionStore = PositionStoreState & PositionStoreActions527528const createPositionStore = () => {529 return createStore<PositionStore>()((set) => ({530 position: { x: 0, y: 0 },531 setPosition: (position) => set({ position }),532 }))533}534535const PositionStoreContext = createContext<ReturnType<536 typeof createPositionStore537> | null>(null)538539function PositionStoreProvider({ children }: { children: ReactNode }) {540 const [store] = useState(() => createPositionStore())541 return (542 <PositionStoreContext.Provider value={store}>543 {children}544 </PositionStoreContext.Provider>545 )546}547548function usePositionStore<U>(selector: (state: PositionStore) => U) {549 const store = useContext(PositionStoreContext)550551 if (store === null) {552 throw new Error(553 'usePositionStore must be used within PositionStoreProvider',554 )555 }556557 return useStore(store, selector)558}559560function MovingDot({ color }: { color: string }) {561 const position = usePositionStore((state) => state.position)562 const setPosition = usePositionStore((state) => state.setPosition)563564 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}596597export 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```610611### Using dynamic scoped (non-global) vanilla stores in React612613First, we'll create a factory function that generates a store for managing the counter state.614Each tab will have its own instance of this store.615616```ts617import { createStore } from 'zustand'618619type CounterState = {620 count: number621}622623type CounterActions = { increment: () => void }624625type CounterStore = CounterState & CounterActions626627const createCounterStore = () => {628 return createStore<CounterStore>()((set) => ({629 count: 0,630 increment: () => {631 set((state) => ({ count: state.count + 1 }))632 },633 }))634}635```636637Next, we'll create a factory function that manages the creation and retrieval of counter stores.638This allows each tab to have its own independent counter.639640```ts641const 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```652653Next, we need a way to manage and access these stores throughout our app. We’ll use React’s context654for this.655656```tsx657const CounterStoresContext = createContext(null)658659const CounterStoresProvider = ({ children }) => {660 const [stores] = useState(661 () => new Map<string, ReturnType<typeof createCounterStore>>(),662 )663664 return (665 <CounterStoresContext.Provider value={stores}>666 {children}667 </CounterStoresContext.Provider>668 )669}670```671672Now, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a673given tab.674675```tsx676const useCounterStore = <U>(677 currentTabIndex: number,678 selector: (state: CounterStore) => U,679) => {680 const stores = useContext(CounterStoresContext)681682 if (stores === undefined) {683 throw new Error('useCounterStore must be used within CounterStoresProvider')684 }685686 const getOrCreateCounterStoreByKey = useCallback(687 () => createCounterStoreFactory(stores),688 [stores],689 )690691 return useStore(getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`))692}693```694695Now, let’s build the Tabs component, where users can switch between tabs and increment each tab’s696counter.697698```tsx699function Tabs() {700 const [currentTabIndex, setCurrentTabIndex] = useState(0)701 const counterState = useCounterStore(702 `tab-${currentTabIndex}`,703 (state) => state,704 )705706 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```761762Finally, we'll create the `App` component, which renders the tabs and their respective counters.763The counter state is managed independently for each tab.764765```tsx766export default function App() {767 return (768 <CounterStoresProvider>769 <Tabs />770 </CounterStoresProvider>771 )772}773```774775Here is what the code should look like:776777```tsx778import {779 type ReactNode,780 useState,781 useCallback,782 useContext,783 createContext,784} from 'react'785import { createStore, useStore } from 'zustand'786787type CounterState = {788 count: number789}790791type CounterActions = { increment: () => void }792793type CounterStore = CounterState & CounterActions794795const createCounterStore = () => {796 return createStore<CounterStore>()((set) => ({797 count: 0,798 increment: () => {799 set((state) => ({ count: state.count + 1 }))800 },801 }))802}803804const 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}814815const CounterStoresContext = createContext<Map<816 string,817 ReturnType<typeof createCounterStore>818> | null>(null)819820const CounterStoresProvider = ({ children }: { children: ReactNode }) => {821 const [stores] = useState(822 () => new Map<string, ReturnType<typeof createCounterStore>>(),823 )824825 return (826 <CounterStoresContext.Provider value={stores}>827 {children}828 </CounterStoresContext.Provider>829 )830}831832const useCounterStore = <U,>(833 key: string,834 selector: (state: CounterStore) => U,835) => {836 const stores = useContext(CounterStoresContext)837838 if (stores === undefined) {839 throw new Error('useCounterStore must be used within CounterStoresProvider')840 }841842 const getOrCreateCounterStoreByKey = useCallback(843 (key: string) => createCounterStoreFactory(stores!)(key),844 [stores],845 )846847 return useStore(getOrCreateCounterStoreByKey(key), selector)848}849850function Tabs() {851 const [currentTabIndex, setCurrentTabIndex] = useState(0)852 const counterState = useCounterStore(853 `tab-${currentTabIndex}`,854 (state) => state,855 )856857 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}911912export default function App() {913 return (914 <CounterStoresProvider>915 <Tabs />916 </CounterStoresProvider>917 )918}919```920921## Troubleshooting922923TBD