PackagesXState Store
@xstate/store-preact
The @xstate/store-preact package provides Preact bindings for XState Store. It includes hooks for subscribing to store state, similar to the React bindings.
This package re-exports all of @xstate/store, so you only need to install @xstate/store-preact.
Installation
npm install @xstate/store-preactpnpm install @xstate/store-preactyarn add @xstate/store-preactQuick start
import { createStore, useSelector } from '@xstate/store-preact';
const store = createStore({
context: { count: 0 },
on: {
inc: (context, event: { by?: number }) => ({
count: context.count + (event.by ?? 1),
}),
},
});
function Counter() {
const count = useSelector(store, (state) => state.context.count);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => store.trigger.inc()}>+1</button>
<button onClick={() => store.trigger.inc({ by: 5 })}>+5</button>
</div>
);
}API
useSelector(store, selector?, compare?)
Subscribes to a store and returns a selected value. The component re-renders when the selected value changes.
import { useSelector } from '@xstate/store-preact';
function Counter() {
// Select specific value
const count = useSelector(store, (state) => state.context.count);
// With custom comparison function
const user = useSelector(
store,
(state) => state.context.user,
(prev, next) => prev.id === next.id
);
return <div>Count: {count}</div>;
}Parameters:
store- The store to subscribe toselector- Optional function to select a value from the store snapshotcompare- Optional comparison function (defaults to strict equality===)
Returns: The selected value
Full documentation
For complete XState Store documentation including context, transitions, effects, atoms, and more, see the XState Store docs.