useStoreContext
A hook used to access a store context created with createStoreContext.
It will throw an error if the context value is null.
const store = useStoreContext(StoreContext, select?);Parameters
Section titled “Parameters”StoreContext- The context of the store.select?- A function to select a subset of the state. Can prevent unnecessary re-renders.
Returns
Section titled “Returns”The store instance.
state- The current state of the store.get- Returns the current state of the store.set- Sets the state of the store.reset- Resets the state of the store to its initial value.initialState- The initial state of the store.actions- Actions that can modify the state of the store (if provided).subscribe- Subscribes to changes in the state of the store. Returns an unsubscribe function.
Basic example
Section titled “Basic example”import { useStoreContext } from "dharma-react";import { StoreContext } from "./store";
function Counter() { const { state: { count }, actions: { increment, decrement }, } = useStoreContext(StoreContext);
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 { state: count } = useStoreContext(StoreContext, (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.