useStore
stableReact hook for qortex-store
Subscribe to a store from React components with selector and equality support.
Signature
useStore<T, U = T>(store: Store<T>,selector?: (state: T) => U,equalityFn?: (a: U, b: U) => boolean,): U
Parameters
store
Store<T>RequiredA store created with createStore from qortex-store
selector
(state: T) => UDefault: identityPicks a slice of state; defaults to returning the full state
equalityFn
(a: U, b: U) => booleanDefault: Object.isCustom equality function to skip unnecessary re-renders
Returns
Returns
UThe selected state slice, kept in sync with the store
Examples
Full State
Access the entire store state (re-renders on any change):
import { useStore } from 'qortex-store-react';import { counterStore } from './stores';function Counter() {const state = useStore(counterStore);return <p>Count: {state.count}</p>;}
Selector
Select only the slice you need to minimize re-renders:
function CountDisplay() {const count = useStore(counterStore, (s) => s.count);return <p>Count: {count}</p>;}function Actions() {const increment = useStore(counterStore, (s) => s.increment);return <button onClick={increment}>+1</button>;}
Custom Equality
Use a shallow-equal function when selecting object slices:
import { shallow } from 'some-shallow-equal';function UserInfo() {const { name, email } = useStore(userStore,(s) => ({ name: s.name, email: s.email }),shallow,);return <p>{name} ({email})</p>;}
Multiple Components
Different components can select different slices of the same store:
function Header() {const name = useStore(userStore, (s) => s.name);return <h1>Hello, {name}</h1>;}function Settings() {const theme = useStore(userStore, (s) => s.theme);return <p>Theme: {theme}</p>;}