Skip to main content
Creates a state machine (statechart) with the given configuration. The state machine represents the pure logic of a state machine actor.

Signature

function createMachine<
  TContext extends MachineContext,
  TEvent extends AnyEventObject,
  TActor extends ProvidedActor,
  TAction extends ParameterizedObject,
  TGuard extends ParameterizedObject,
  TDelay extends string,
  TTag extends string,
  TInput,
  TOutput extends NonReducibleUnknown,
  TEmitted extends EventObject,
  TMeta extends MetaObject
>(
  config: MachineConfig<...>,
  implementations?: InternalMachineImplementations<...>
): StateMachine<...>

Parameters

config
MachineConfig
required
The state machine configuration object.
implementations
InternalMachineImplementations
DEPRECATED: Use setup({ ... }) or machine.provide({ ... }) to provide machine implementations instead.Optional implementations for actions, guards, actors, and delays referenced in the machine config.

Returns

machine
StateMachine
A StateMachine instance representing the state machine logic.

Examples

Basic state machine

import { createMachine } from 'xstate';

const lightMachine = createMachine({
  id: 'light',
  initial: 'green',
  states: {
    green: {
      on: {
        TIMER: { target: 'yellow' }
      }
    },
    yellow: {
      on: {
        TIMER: { target: 'red' }
      }
    },
    red: {
      on: {
        TIMER: { target: 'green' }
      }
    }
  }
});

const lightActor = createActor(lightMachine);
lightActor.start();

lightActor.send({ type: 'TIMER' });

Machine with context

import { createMachine } from 'xstate';

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

Machine with TypeScript types

import { createMachine } from 'xstate';

type Context = { count: number };
type Events = 
  | { type: 'INCREMENT' }
  | { type: 'DECREMENT' };

const machine = createMachine({
  types: {} as {
    context: Context;
    events: Events;
  },
  initial: 'active',
  context: { count: 0 },
  states: {
    active: {
      on: {
        INCREMENT: {
          actions: assign({
            count: ({ context }) => context.count + 1
          })
        }
      }
    }
  }
});

Machine with final state and output

import { createMachine } from 'xstate';

const fetchMachine = createMachine({
  id: 'fetch',
  initial: 'idle',
  context: { data: null },
  states: {
    idle: {
      on: {
        FETCH: 'loading'
      }
    },
    loading: {
      on: {
        SUCCESS: 'success'
      }
    },
    success: {
      type: 'final'
    }
  },
  output: ({ context }) => context.data
});

See also