Skip to content
Version: XState v4

Actor cheatsheet

Get working quickly with actors using our quick reference cheatsheet.

Import spawn to spawn actors

Import spawn to spawn actors:

import { spawn } from 'xstate';

Spawn actors in assign action creators

Spawn actors in assign action creators:

// ...
{
actions: assign({
someRef: (context, event) => spawn(someMachine)
});
}
// ...

Spawn different types of actors

Spawn different types of actors:

// ...
{
actions: assign({
// From a promise
promiseRef: (context, event) =>
spawn(
new Promise((resolve, reject) => {
// ...
}),
'my-promise'
),

// From a callback
callbackRef: (context, event) =>
spawn((callback, receive) => {
// send to parent
callback('SOME_EVENT');

// receive from parent
receive((event) => {
// handle event
});

// disposal
return () => {
/* do cleanup here */
};
}),

// From an observable
observableRef: (context, event) => spawn(someEvent$),

// From a machine
machineRef: (context, event) =>
spawn(
createMachine({
// ...
})
)
});
}
// ...

Sync state with an actor

Sync state with an actor:

// ...
{
actions: assign({
someRef: () => spawn(someMachine, { sync: true })
});
}
// ...

Get a snapshot from an actor

Get a snapshot from an actor:

service.onTransition((state) => {
const { someRef } = state.context;

someRef.getSnapshot();
// => State { ... }
});

Send event to actor with send action creator

Send an event to an actor with the send action creator:

// ...
{
actions: send(
{ type: 'SOME_EVENT' },
{
to: (context) => context.someRef
}
);
}
// ...

Send event with data to actor using a send expression

Send an event with data to an actor using the send expression:

// ...
{
actions: send((context, event) => ({ ...event, type: 'SOME_EVENT' }), {
to: (context) => context.someRef
});
}
// ...

Send event from actor to parent with sendParent action creator

Send an event from an actor to its parent with the sendParent action creator:

// ...
{
actions: sendParent({ type: 'ANOTHER_EVENT' });
}
// ...

Send event with data from actor to parent using a sendParent expression

Send an event with data from an actor to its parent using the sendParent expression:

// ...
{
actions: sendParent((context, event) => ({
...context,
type: 'ANOTHER_EVENT'
}));
}
// ...

Reference actors from context

Reference actors from context:

someService.onTransition((state) => {
const { someRef } = state.context;

console.log(someRef);
// => { id: ..., send: ... }
});