useStore
A hook used to access a store created with createStore and bind it to a component.
const state = useStore(store, select?);Parameters
Section titled “Parameters”store- The store created withcreateStoreor a derived store fromderive.select?- A function to select a subset of the state. Can prevent unnecessary re-renders.
Returns
Section titled “Returns”The selected state from the store.
Basic example
Section titled “Basic example”import { useStore } from "dharma-react";import { store } from "./store";
const { increment, decrement } = store.actions;
function Counter() { const { count } = useStore(store);
return ( <div> <div>{count}</div> <button onClick={decrement}>-</button> <button onClick={increment}>+</button> </div> );}With a select function
Section titled “With a select function”const count = useStore(store, (state) => state.count);Note: If the select function is provided, an equality check is performed. For optimal performance, return a direct reference to the state. (e.g. state.count)
If you wish to select multiple values, return an object or an array. (e.g. { count: state.count, name: state.name } or [state.count, state.name])
Other unstable reference types will cause infinite loops.
Server-side rendering
Section titled “Server-side rendering”When rendering on the server, persisted stores should set syncWithStorageOn to "attach" to avoid hydration mismatches. See Persisting state with SSR.