@xstate/react package provides React hooks and utilities for using XState actors in React applications.
Installation
Requirements
- React 16.8.0 or higher (requires hooks support)
- XState 5.0.0 or higher
Available Hooks
The package exports the following hooks:Core Hooks
useActor- Create and subscribe to an actor from logicuseActorRef- Create an actor ref without subscribing to state changesuseSelector- Subscribe to derived state from an actor
Context Utilities
createActorContext- Create React context for sharing actors across components
Quick Start
Basic Usage with useActor
Using Context for Shared State
Optimizing Re-renders with useSelector
Server-Side Rendering
All hooks are compatible with server-side rendering (SSR). The package usesuse-sync-external-store shim to ensure compatibility with React 18’s concurrent features and SSR.
Migration from v4
If you’re upgrading from@xstate/react v4:
useMachinehas been deprecated in favor ofuseActoruseInterprethas been deprecated in favor ofuseActorRef- Actor refs are now automatically started and stopped
- The third return value from
useActoris now the actor ref instead of the service
Next Steps
- Learn about useActor for component state management
- Optimize performance with useSelector
- Share state across components with createActorContext