@xstate/store-react
v1.0.1
Published
XState Store for React
Downloads
2,461
Readme
@xstate/store-react
React adapter for @xstate/store.
Installation
npm install @xstate/store-reactQuickstart
import { createStore, useSelector } from '@xstate/store-react';
// ...
const store = createStore({
context: { count: 0 },
on: {
inc: (ctx) => ({ ...ctx, count: ctx.count + 1 })
}
});
const App = () => {
const count = useSelector(store, (s) => s.context.count);
return (
<button onClick={() => store.send({ type: 'inc' })}>Count: {count}</button>
);
};API
useSelector(store, selector?, compare?)
Subscribes to a store and returns a selected value.
import { createStore, useSelector } from '@xstate/store-react';
// ...
const store = createStore({
context: { count: 0 },
on: {
inc: (ctx) => ({ ...ctx, count: ctx.count + 1 })
}
});
const App = () => {
const count = useSelector(store, (s) => s.context.count);
// or without selector (returns full snapshot)
const snapshot = useSelector(store);
// ...
};Arguments:
store- Store created withcreateStore()selector?- Function to select a value from snapshotcompare?- Equality function (default:===)
Returns: Selected value (re-renders on change)
useStore(definition)
Creates a store instance scoped to a component.
import { useStore, useSelector } from '@xstate/store-react';
// ...
const App = () => {
const store = useStore({
context: { count: 0 },
on: {
inc: (ctx) => ({ ...ctx, count: ctx.count + 1 })
}
});
const count = useSelector(store, (s) => s.context.count);
// ...
};Arguments:
definition- Store configuration object
Returns: Store instance (stable across re-renders)
useAtom(atom, selector?, compare?)
Subscribes to an atom and returns its value.
import { createAtom, useAtom } from '@xstate/store-react';
// ...
const countAtom = createAtom(0);
const App = () => {
const count = useAtom(countAtom);
return <button onClick={() => countAtom.set((c) => c + 1)}>{count}</button>;
};Arguments:
atom- Atom created withcreateAtom()selector?- Selector functioncompare?- Equality function
Returns: Atom value (re-renders on change)
createStoreHook(definition)
Creates a custom hook that returns [selectedValue, store].
import { createStoreHook } from '@xstate/store-react';
// ...
const useCountStore = createStoreHook({
context: { count: 0 },
on: {
inc: (ctx, e: { by: number }) => ({ ...ctx, count: ctx.count + e.by })
}
});
const App = () => {
const [count, store] = useCountStore((s) => s.context.count);
return <button onClick={() => store.trigger.inc({ by: 1 })}>{count}</button>;
};Arguments:
definition- Store configuration object
Returns: Custom hook function
Re-exports
All exports from @xstate/store are re-exported, including createStore, createStoreWithProducer, createAtom, and more.
See the XState Store docs for the full API, and the React-specific docs for more React examples.
