What are Actors?
In XState, actors are self-contained units of logic that:- Receive events
- Maintain their own state (context)
- Send events to other actors
- Can be started, stopped, and supervised
- Communicate exclusively through message passing
Actor Types
XState provides four primary actor logic creators:Promise Actors
For asynchronous operations that resolve once with a value.Callback Actors
For subscription-based or event-driven logic.Observable Actors
For reactive streams and observables (RxJS compatible).Transition Actors
For reducer-style state management.Creating and Using Actors
Basic Actor Lifecycle
Providing Input
All actor types can receive input:Invoking Actors in Machines
Actors are commonly invoked from state machines:Actor Communication
Sending Events to Parent
Receiving Events
Sending Events to Actors
Actor Snapshots
Each actor type produces snapshots with different properties:Promise Snapshot
Callback Snapshot
Observable Snapshot
Transition Snapshot
Actor System
Actors exist within an actor system that manages communication:Emitting Custom Events
Actors can emit custom events to subscribers:Best Practices
-
Choose the right actor type:
- Use
fromPromisefor one-time async operations - Use
fromCallbackfor subscriptions and event listeners - Use
fromObservablefor reactive streams - Use
fromTransitionfor reducer-style state management
- Use
- Clean up resources: Return cleanup functions from callback actors
- Type your actors: Provide type parameters for type safety
- Handle errors: Subscribe to error events or use onError handlers
- Use input for configuration: Pass initial data via input rather than closures
See Also
- fromPromise - Promise-based actors
- fromCallback - Callback-based actors
- fromObservable - Observable-based actors
- fromTransition - Transition-based actors