Skip to content
Version: XState v5

Quick start

Want to jump straight into XState version 5 and Stately Studio? Start here! Below you’ll find the quickest way to get started with XState using the example of a toggle feature and links to more detailed documentation.

Installing XState V5 beta​

XState is a visual state management and orchestration library for JavaScript and TypeScript.

Install the XState V5 beta using your preferred package manager:

yarn add xstate@beta

Create a machine​

Read our introduction to state machines and statecharts to familiarize yourself with the concepts.

import { createMachine } from 'xstate';

const toggleMachine = createMachine({
id: 'toggle',
initial: 'Inactive',
states: {
Inactive: {
on: { toggle: 'Active' },
},
Active: {
on: { toggle: 'Inactive' },
},
},
});

Interpret your machine and send it events​

When you run a state machine, it becomes an actor: a running process that can receive messages (events), send messages and change its behavior based on the messages it receives, which can cause effects outside of the actor.

import { createMachine, interpret } from 'xstate';

const toggleMachine = createMachine({
// Machine code from above
});

// Creates an actor that you can send events to; not started yet!
const actor = interpret(machine);

// Subscribe to updated snapshots (emitted state changes) from the actor
actor.subscribe((snapshot) => {
console.log('Value:', snapshot.value);
});

// Start the actor!
actor.start(); // logs 'Inactive'

// Send events
actor.send({ type: 'toggle' }); // logs 'Active'
actor.send({ type: 'toggle' }); // logs 'Inactive'

Use delayed transitions​

Delayed transitions are transitions that only happen after a specified interval of time.

export const toggleMachine = createMachine({
id: 'toggle',
initial: 'Inactive',
states: {
Inactive: {
on: { toggle: 'Active' },
},
Active: {
on: { toggle: 'Inactive' },
after: { 2000: 'Inactive' },
},
},
});

Handle context data​

Context is how you store data in a state machine actor.

import { assign, createMachine } from 'xstate';

export const toggleMachine = createMachine({
id: 'toggle',
context: { count: 0 },
initial: 'Inactive',
states: {
Inactive: {
on: { toggle: 'Active' },
},
Active: {
entry: assign({ count: ({ context }) => context.count + 1 }),
on: { toggle: 'Inactive' },
after: { 2000: 'Inactive' },
},
},
});

Use your machine with a framework​

import { useMachine } from '@xstate/react';
import { toggleMachine } from './toggleMachine';

const App = () => {
const [state, send] = useMachine(toggleMachine);

return (
<div>
<div>Value: {state.value}</div>
<button onClick={() => send({ type: 'toggle' })}>Toggle</button>
</div>
);
};