Actors in XState
Learn all about using actors in XState.
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.
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:
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:
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.
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.
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.
Get working quickly with actors using our quick reference cheatsheet.