Skip to content
Version: XState v5

State machine actors

State machine actors are actors whose logic is represented by a finite state machine or statechart.

State machine actor capabilities​

CapabilityNotes
✅Receive eventsState machine actors can receive events directly (actor.send(event)) or from other actors.
✅Send eventsState machine actors can send events to other actors it has reference to.
✅Spawn actorsState machine actors can spawn/invoke actors and have child actors.
✅InputYou can provide input to state machine actors.
✅OutputState machine actors can produce output.

State machine actor logic​

You can define state machine actor logic using the createMachine(...) actor logic creator, which takes a finite state machine or statechart configuration object as its only argument.

import { createMachine, createActor } from 'xstate';

const toggleMachine = createMachine({
initial: 'inactive',
states: {
inactive: {
on: {
toggle: {
target: 'active'
}
}
},
active: {
on: {
toggle: {
target: 'inactive'
}
}
}
}
});

const toggleActor = createActor(toggleMachine);
toggleActor.subscribe(snapshot => {
console.log(snapshot.value); // 'inactive' or 'active'
});
toggleActor.start();
// logs 'inactive'

toggleActor.send({ type: 'toggle' });
// logs 'active'

toggleActor.send({ type: 'toggle' });
// logs 'inactive'

State machine actor input​

You can pass in input to a state machine actor by passing it to the createActor(...) function as the input property of the second argument. In the state machine (setupFiles(…).createMachine(…)), you read the input property of the first argument passed to the context function:

import { setup, createActor } from 'xstate';

const feedbackMachine = setup({
// ...
}).createMachine({
context: ({ input }) => ({
rating: input.defaultRating
}),
initial: 'question',
states: {
question: {/* ... */},
// ...
}
});

const feedbackActor = createActor(feedbackMachine, {
input: {
defaultRating: 3
}
});

feedbackActor.subscribe(snapshot => {
console.log(snapshot.context);
});

feedbackActor.start();
// logs { rating: 3 }

State machine actor output​

Read state machine output for more information.