Skip to main content
Creates a new actor instance for the given actor logic with the provided options. When you create an actor from actor logic via createActor(logic), you implicitly create an actor system where the created actor is the root actor. Any actors spawned from this root actor and its descendants are part of that actor system.

Signature

function createActor<TLogic extends AnyActorLogic>(
  logic: TLogic,
  options?: ActorOptions<TLogic>
): Actor<TLogic>

Parameters

logic
ActorLogic
required
The actor logic to create an actor from.Actor logic can be:
  • A state machine created with createMachine()
  • Promise logic created with fromPromise()
  • Callback logic created with fromCallback()
  • Observable logic created with fromObservable() or fromEventObservable()
  • Transition logic created with fromTransition()
options
ActorOptions
Optional configuration for the actor.

Returns

actor
Actor<TLogic>
An Actor instance that can receive events, send events, and change its behavior.

Examples

Creating and starting an actor

import { createActor, createMachine } from 'xstate';

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

// Create the actor
const actor = createActor(toggleMachine);

// Subscribe to state changes
actor.subscribe((snapshot) => {
  console.log('State:', snapshot.value);
});

// Start the actor
actor.start();
// Logs: State: inactive

// Send events
actor.send({ type: 'TOGGLE' });
// Logs: State: active

// Stop the actor
actor.stop();

Actor with input

import { createActor, createMachine } from 'xstate';

const greetMachine = createMachine({
  types: {} as {
    context: { name: string; count: number };
    input: { name: string };
  },
  context: ({ input }) => ({
    name: input.name,
    count: 0
  }),
  initial: 'greeting',
  states: {
    greeting: {
      entry: ({ context }) => {
        console.log(`Hello, ${context.name}!`);
      }
    }
  }
});

const actor = createActor(greetMachine, {
  input: { name: 'Alice' }
});

actor.start();
// Logs: Hello, Alice!

Actor with inspection

import { createActor, createMachine } from 'xstate';

const machine = createMachine({
  initial: 'idle',
  states: {
    idle: {
      on: { START: 'running' }
    },
    running: {}
  }
});

const actor = createActor(machine, {
  inspect: (inspectionEvent) => {
    if (inspectionEvent.type === '@xstate.event') {
      console.log('Event:', inspectionEvent.event);
    }
    
    if (inspectionEvent.type === '@xstate.snapshot') {
      console.log('Snapshot:', inspectionEvent.snapshot.value);
    }
  }
});

actor.start();
actor.send({ type: 'START' });

Persisting and restoring actor state

import { createActor, createMachine } from 'xstate';

const counterMachine = createMachine({
  initial: 'active',
  context: { count: 0 },
  states: {
    active: {
      on: {
        INCREMENT: {
          actions: assign({ count: ({ context }) => context.count + 1 })
        }
      }
    }
  }
});

// Create and use the actor
const actor1 = createActor(counterMachine);
actor1.start();
actor1.send({ type: 'INCREMENT' });
actor1.send({ type: 'INCREMENT' });

// Persist the state
const persistedState = actor1.getPersistedSnapshot();

// Later, restore the state
const actor2 = createActor(counterMachine, {
  snapshot: persistedState
});
actor2.start();

console.log(actor2.getSnapshot().context.count); // 2

Using different actor logics

import { createActor, fromPromise, fromCallback } from 'xstate';

// Promise actor
const promiseLogic = fromPromise(async ({ input }: { input: number }) => {
  const response = await fetch(`/api/data/${input}`);
  return response.json();
});

const promiseActor = createActor(promiseLogic, { input: 42 });
promiseActor.start();

// Callback actor
const callbackLogic = fromCallback(({ sendBack }) => {
  const interval = setInterval(() => {
    sendBack({ type: 'TICK' });
  }, 1000);

  return () => clearInterval(interval);
});

const callbackActor = createActor(callbackLogic);
callbackActor.subscribe((snapshot) => {
  console.log('Callback actor snapshot:', snapshot);
});
callbackActor.start();

Notes

  • Actors must be started with .start() before they can receive events or emit snapshots
  • Only root actors (those without a parent) can be stopped with .stop()
  • When an actor is stopped, all of its observers are automatically unsubscribed
  • The actor system is created when the root actor is created and manages all spawned child actors

See also