JS State Machines
with XState

David Khourshid - @davidkpiano

Behaviors

How should the system react?

Events

What can happen in the system?

"States"

Given [precondition]

When [action]

Then [postcondition]

Asleep

Awake

Wake up

User Flows
& Flowcharts

State Machines
& Statecharts

Visual formalisms are diagrammatic and intuitive, yet mathematically rigorous languages. Thus, despite their clear visual appearance, they come complete with a syntax that determines what is allowed, and semantics that determines what the allowed things mean.

David Harel

On Visual Formalisms

Callbacks

Event handlers

Ad-hoc logic

Ad-hoc logic

Reducer

EVENT

EVENT

EVENT

EVENT

State machine

EVENT

EVENT

EVENT

Statechart

Actors

npm install xstate

idle

searching

success

failure

SEARCH

RESOLVE

REJECT

SEARCH

SEARCH

npm install xstate
import { createMachine } from 'xstate';

const machine = createMachine({
  initial: 'idle',
  states: {
    idle: {
      on: { SEARCH: 'searching' }
    },
    searching: {
      on: {
        RESOLVE: 'success',
        REJECT: 'failure',
      }
    },
    success: {
      on: { SEARCH: 'searching' }
    },
    failure: {
      on: { SEARCH: 'searching' }
    }
  }
});
npm install xstate
import { createMachine } from 'xstate';

const machine = createMachine({
  // ...
});

const searchingState = machine
  .transition('idle', 'SEARCH');

searchingState.value;
// => 'searching'
npm install xstate
import { createMachine, interpret } from 'xstate';

const machine = createMachine({
  // ...
});

const service = interpret(machine)
  .onTransition(state => console.log(state))
  .start();

service.send('SEARCH');
// State {
//   value: 'searching',
//   ...
// }

State management

State orchestration

  • @xstate/fsm
  • @xstate/test
  • @xstate/graph
  • @xstate/inspect
  • @xstate/react ⚛️
  • @xstate/vue 💚
  • @xstate/svelte 🧡

Current Modules

  • @xstate/fsm
  • @xstate/test
  • @xstate/graph
  • @xstate/inspect
  • @xstate/react ⚛️
  • @xstate/vue 💚
  • @xstate/svelte 🧡
  • @xstate/parser
  • @xstate/angular 
  • @xstate/cli
  • @xstate/form
  • @xstate/router
  • @xstate/query
  • @xstate/temporal

Current Modules

Future Ideas

stately.ai/editor

Thank you!

David Khourshid - @davidkpiano

JS State Machines with XState

By David Khourshid

JS State Machines with XState

  • 1,435