Actors in XState
Learn all about using actors in XState.
Introducing actors
When you run a statechart, it becomes an actor, a running process that can receive events. Often, you’ll need your actor to run other actors; spawning new statecharts, waiting for promises, or subscribing to observables.
Promises
The most common type of actors you’ll invoke are promise actors. Promise actors allow you to await the result of a promise before deciding what to do next.
Actions vs. actors
Sometimes it’s unclear whether you should use an action or an actor. Both appear to do similar things, executing side effects. Let’s break down the differences:
Callbacks
Promise actors let you model promises declaratively but not every actor will be a promise. Callback actors give you a flexible API for managing a long-running actor that can do several things a promise can’t, like:
Machines
Callback actors are one way to start invoking long-lived actors and are useful for simple to intermediate cases. But sometimes, you’ll want to use all the power of a statechart.
Observables
Observables are streams of values emitted over time. They could be considered an array or collection whose values are emitted asynchronously instead of all at once. There are many implementations of observables in JavaScript; the most popular one is RxJS.
Parent to child communication
We’ve learned that invoked actors can send events to their parent via the invoked machine’s sendParent action and the invoked callback’s sendBack method. Child actors can also receive events from the parent, allowing for bidirectional communication.
Spawning actors
Sometimes invoking actors may not be flexible enough for your needs. In such cases, you might want to invoke child machines that last across several states or invoke a dynamic number of actors.
Actor cheatsheet
Get working quickly with actors using our quick reference cheatsheet.