What is XState Store?
XState Store provides:- Simple stores - Manage state with a context object and event-based transitions
- Type-safe events - Full TypeScript support with inferred event types
- Reactive subscriptions - Subscribe to state changes and derived values
- Framework integrations - First-class support for React, Solid, and Vue
- Atoms - Fine-grained reactive primitives for computed values
- XState interop - Use stores as actors in XState machines
Installation
Quick Example
Core Concepts
Context
Thecontext is your store’s state. It’s a plain object that holds all your application data:
Events and Transitions
Events trigger transitions that update context. Each event handler receives the current context and event payload:Snapshots
Callingstore.getSnapshot() or store.get() returns a snapshot with:
The snapshot structure matches XState’s snapshot format, making stores compatible with XState actors.
When to Use XState Store
Use XState Store when:
- You need simple, event-driven state management
- Your state updates follow predictable patterns
- You want type-safe state and events
- You need fine-grained reactivity with selectors
- You’re building a new app without complex workflows
Use XState (state machines) when:
- You have complex state transitions with guards and conditions
- Your logic involves sequential workflows or multi-step processes
- You need state charts for visualization
- You require advanced features like actors, spawning, and hierarchical states
- Your domain has many possible states and transitions between them
Store vs Redux
If you’re familiar with Redux:| Feature | XState Store | Redux |
|---|---|---|
| State updates | Event handlers return new context | Reducers with actions |
| Immutability | Manual spreading or Immer | Manual spreading |
| Type safety | Inferred from event handlers | Requires manual typing |
| Middleware | Effects via enqueue | Middleware |
| DevTools | XState inspector | Redux DevTools |
| Side effects | Built-in with enqueue.effect() | Requires middleware |