Function useStoreContext

A hook used to access a store context created with createStoreContext.

Basic usage:

import { useStoreContext } from "@fransek/statekit";
import { StoreContext } from "./store";

function Counter() {
const {
state: { count },
actions: { increment, decrement, reset },
} = useStoreContext(StoreContext);

return (
<div>
<div>{count}</div>
<button onClick={decrement}>-</button>
<button onClick={increment}>+</button>
<button onClick={reset}>Reset</button>
</div>
);
}

With a select function:

const {
state: { count },
} = useStoreContext(GlobalStoreContext, (state) => state.counter);

If the select function is provided, an equality check is performed. This has some caveats:

  • For optimal performance, return a direct reference to the state. (e.g. state.count)
  • If you return an object literal, it should only contain direct references to the state. (e.g. { count: state.count })