function createStoreContext<TValue>(): object;
function createStoreContext<TValue>(): object;
Defined in: packages/react-store/src/createStoreContext.tsx:40
Creates a typed React context for sharing a bundle of atoms and stores with a subtree.
The returned StoreProvider only transports the provided object through React context. Consumers destructure the contextual atoms and stores, then compose them with the existing hooks like useSelector, useSelector and useAtom.
The object shape is preserved exactly, so keyed atoms and stores remain fully typed when read back with useStoreContext().
TValue extends object
object
StoreProvider: (props) => ReactElement;
StoreProvider: (props) => ReactElement;
object & object
ReactElement
useStoreContext: () => TValue;
useStoreContext: () => TValue;
TValue
const { StoreProvider, useStoreContext } = createStoreContext<{
countAtom: Atom<number>
totalsStore: Store<{ count: number }>
}>()
function CountButton() {
const { countAtom, totalsStore } = useStoreContext()
const count = useSelector(countAtom)
const total = useSelector(totalsStore, (state) => state.count)
return (
<button
type="button"
onClick={() => totalsStore.setState((state) => ({ ...state, count: state.count + 1 }))}
>
{count} / {total}
</button>
)
}
const { StoreProvider, useStoreContext } = createStoreContext<{
countAtom: Atom<number>
totalsStore: Store<{ count: number }>
}>()
function CountButton() {
const { countAtom, totalsStore } = useStoreContext()
const count = useSelector(countAtom)
const total = useSelector(totalsStore, (state) => state.count)
return (
<button
type="button"
onClick={() => totalsStore.setState((state) => ({ ...state, count: state.count + 1 }))}
>
{count} / {total}
</button>
)
}
When useStoreContext() is called outside the matching StoreProvider.
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.