XState

State machines and statecharts for the modern web.

README


XState logotype
JavaScript state machines and statecharts

npm version

JavaScript and TypeScript finite state machines and statecharts for the modern web.





📑 Adheres to the SCXML specification

💬 Chat on the Stately Discord Community

Packages


- 🤖 xstate - Core finite state machine and statecharts library + interpreter
- [🔬 @xstate/fsm](https://github.com/statelyai/xstate/tree/main/packages/xstate-fsm) - Minimal finite state machine library
- [📉 @xstate/graph](https://github.com/statelyai/xstate/tree/main/packages/xstate-graph) - Graph traversal utilities for XState
- [⚛️ @xstate/react](https://github.com/statelyai/xstate/tree/main/packages/xstate-react) - React hooks and utilities for using XState in React applications
- [💚 @xstate/vue](https://github.com/statelyai/xstate/tree/main/packages/xstate-vue) - Vue composition functions and utilities for using XState in Vue applications
- [🎷 @xstate/svelte](https://github.com/statelyai/xstate/tree/main/packages/xstate-svelte) - Svelte utilities for using XState in Svelte applications
- [✅ @xstate/test](https://github.com/statelyai/xstate/tree/main/packages/xstate-test) - Model-Based-Testing utilities (using XState) for testing any software
- [🔍 @xstate/inspect](https://github.com/statelyai/xstate/tree/main/packages/xstate-inspect) - Inspection utilities for XState

Templates


Get started by forking one of these templates on CodeSandbox:

- XState Template - no framework

Super quick start


  1. ``` sh
  2. npm install xstate
  3. ```

  1. ``` js
  2. import { createMachine, interpret } from 'xstate';

  3. // Stateless machine definition
  4. // machine.transition(...) is a pure function used by the interpreter.
  5. const toggleMachine = createMachine({
  6.   id: 'toggle',
  7.   initial: 'inactive',
  8.   states: {
  9.     inactive: { on: { TOGGLE: 'active' } },
  10.     active: { on: { TOGGLE: 'inactive' } }
  11.   }
  12. });

  13. // Machine instance with internal state
  14. const toggleService = interpret(toggleMachine)
  15.   .onTransition((state) => console.log(state.value))
  16.   .start();
  17. // => 'inactive'

  18. toggleService.send('TOGGLE');
  19. // => 'active'

  20. toggleService.send('TOGGLE');
  21. // => 'inactive'
  22. ```

Promise example



See the code

  1. ``` js
  2. import { createMachine, interpret, assign } from 'xstate';

  3. const fetchMachine = createMachine({
  4.   id: 'Dog API',
  5.   initial: 'idle',
  6.   context: {
  7.     dog: null
  8.   },
  9.   states: {
  10.     idle: {
  11.       on: {
  12.         FETCH: 'loading'
  13.       }
  14.     },
  15.     loading: {
  16.       invoke: {
  17.         id: 'fetchDog',
  18.         src: (context, event) =>
  19.           fetch('https://dog.ceo/api/breeds/image/random').then((data) =>
  20.             data.json()
  21.           ),
  22.         onDone: {
  23.           target: 'resolved',
  24.           actions: assign({
  25.             dog: (_, event) => event.data
  26.           })
  27.         },
  28.         onError: 'rejected'
  29.       },
  30.       on: {
  31.         CANCEL: 'idle'
  32.       }
  33.     },
  34.     resolved: {
  35.       type: 'final'
  36.     },
  37.     rejected: {
  38.       on: {
  39.         FETCH: 'loading'
  40.       }
  41.     }
  42.   }
  43. });

  44. const dogService = interpret(fetchMachine)
  45.   .onTransition((state) => console.log(state.value))
  46.   .start();

  47. dogService.send('FETCH');
  48. ```



Visualizer



XState Viz


Why?


Statecharts are a formalism for modeling stateful, reactive systems. This is useful for declaratively describing the _behavior_ of your application, from the individual components to the overall application logic.

Read 📽 the slides (🎥 video) or check out these resources for learning about the importance of finite state machines and statecharts in user interfaces:

- The World of Statecharts by Erik Mogensen
- Pure UI by Guillermo Rauch
- Pure UI Control by Adam Solove
- Spectrum - Statecharts Community (For XState specific questions, please use the GitHub Discussions)

Finite State Machines


Finite states
Open in Stately Viz

  1. ``` js
  2. import { createMachine } from 'xstate';

  3. const lightMachine = createMachine({
  4.   id: 'light',
  5.   initial: 'green',
  6.   states: {
  7.     green: {
  8.       on: {
  9.         TIMER: 'yellow'
  10.       }
  11.     },
  12.     yellow: {
  13.       on: {
  14.         TIMER: 'red'
  15.       }
  16.     },
  17.     red: {
  18.       on: {
  19.         TIMER: 'green'
  20.       }
  21.     }
  22.   }
  23. });

  24. const currentState = 'green';

  25. const nextState = lightMachine.transition(currentState, 'TIMER').value;

  26. // => 'yellow'
  27. ```

Hierarchical (Nested) State Machines


Hierarchical states
Open in Stately Viz

  1. ``` js
  2. import { createMachine } from 'xstate';

  3. const pedestrianStates = {
  4.   initial: 'walk',
  5.   states: {
  6.     walk: {
  7.       on: {
  8.         PED_TIMER: 'wait'
  9.       }
  10.     },
  11.     wait: {
  12.       on: {
  13.         PED_TIMER: 'stop'
  14.       }
  15.     },
  16.     stop: {}
  17.   }
  18. };

  19. const lightMachine = createMachine({
  20.   id: 'light',
  21.   initial: 'green',
  22.   states: {
  23.     green: {
  24.       on: {
  25.         TIMER: 'yellow'
  26.       }
  27.     },
  28.     yellow: {
  29.       on: {
  30.         TIMER: 'red'
  31.       }
  32.     },
  33.     red: {
  34.       on: {
  35.         TIMER: 'green'
  36.       },
  37.       ...pedestrianStates
  38.     }
  39.   }
  40. });

  41. const currentState = 'yellow';

  42. const nextState = lightMachine.transition(currentState, 'TIMER').value;
  43. // => {
  44. //   red: 'walk'
  45. // }

  46. lightMachine.transition('red.walk', 'PED_TIMER').value;
  47. // => {
  48. //   red: 'wait'
  49. // }
  50. ```

Object notation for hierarchical states:

  1. ``` js
  2. // ...
  3. const waitState = lightMachine.transition({ red: 'walk' }, 'PED_TIMER').value;

  4. // => { red: 'wait' }

  5. lightMachine.transition(waitState, 'PED_TIMER').value;

  6. // => { red: 'stop' }

  7. lightMachine.transition({ red: 'stop' }, 'TIMER').value;

  8. // => 'green'
  9. ```

Parallel State Machines


Parallel states
Open in Stately Viz

  1. ``` js
  2. const wordMachine = createMachine({
  3.   id: 'word',
  4.   type: 'parallel',
  5.   states: {
  6.     bold: {
  7.       initial: 'off',
  8.       states: {
  9.         on: {
  10.           on: { TOGGLE_BOLD: 'off' }
  11.         },
  12.         off: {
  13.           on: { TOGGLE_BOLD: 'on' }
  14.         }
  15.       }
  16.     },
  17.     underline: {
  18.       initial: 'off',
  19.       states: {
  20.         on: {
  21.           on: { TOGGLE_UNDERLINE: 'off' }
  22.         },
  23.         off: {
  24.           on: { TOGGLE_UNDERLINE: 'on' }
  25.         }
  26.       }
  27.     },
  28.     italics: {
  29.       initial: 'off',
  30.       states: {
  31.         on: {
  32.           on: { TOGGLE_ITALICS: 'off' }
  33.         },
  34.         off: {
  35.           on: { TOGGLE_ITALICS: 'on' }
  36.         }
  37.       }
  38.     },
  39.     list: {
  40.       initial: 'none',
  41.       states: {
  42.         none: {
  43.           on: { BULLETS: 'bullets', NUMBERS: 'numbers' }
  44.         },
  45.         bullets: {
  46.           on: { NONE: 'none', NUMBERS: 'numbers' }
  47.         },
  48.         numbers: {
  49.           on: { BULLETS: 'bullets', NONE: 'none' }
  50.         }
  51.       }
  52.     }
  53.   }
  54. });

  55. const boldState = wordMachine.transition('bold.off', 'TOGGLE_BOLD').value;

  56. // {
  57. //   bold: 'on',
  58. //   italics: 'off',
  59. //   underline: 'off',
  60. //   list: 'none'
  61. // }

  62. const nextState = wordMachine.transition(
  63.   {
  64.     bold: 'off',
  65.     italics: 'off',
  66.     underline: 'on',
  67.     list: 'bullets'
  68.   },
  69.   'TOGGLE_ITALICS'
  70. ).value;

  71. // {
  72. //   bold: 'off',
  73. //   italics: 'on',
  74. //   underline: 'on',
  75. //   list: 'bullets'
  76. // }
  77. ```

History States


History state
Open in Stately Viz

  1. ``` js
  2. const paymentMachine = createMachine({
  3.   id: 'payment',
  4.   initial: 'method',
  5.   states: {
  6.     method: {
  7.       initial: 'cash',
  8.       states: {
  9.         cash: { on: { SWITCH_CHECK: 'check' } },
  10.         check: { on: { SWITCH_CASH: 'cash' } },
  11.         hist: { type: 'history' }
  12.       },
  13.       on: { NEXT: 'review' }
  14.     },
  15.     review: {
  16.       on: { PREVIOUS: 'method.hist' }
  17.     }
  18.   }
  19. });

  20. const checkState = paymentMachine.transition('method.cash', 'SWITCH_CHECK');

  21. // => State {
  22. //   value: { method: 'check' },
  23. //   history: State { ... }
  24. // }

  25. const reviewState = paymentMachine.transition(checkState, 'NEXT');

  26. // => State {
  27. //   value: 'review',
  28. //   history: State { ... }
  29. // }

  30. const previousState = paymentMachine.transition(reviewState, 'PREVIOUS').value;

  31. // => { method: 'check' }
  32. ```

SemVer Policy


We understand the importance of the public contract and do not intend to release any breaking changes to the runtime API in a minor or patch release. We consider this with any changes we make to the XState libraries and aim to minimize their effects on existing users.

Breaking changes


XState executes much of the user logic itself. Therefore, almost any change to its behavior might be considered a breaking change. We recognize this as a potential problem but believe that treating every change as a breaking change is not practical. We do our best to implement new features thoughtfully to enable our users to implement their logic in a better, safer way.

Any change _could_ affect how existing XState machines behave if those machines are using particular configurations. We do not introduce behavior changes on a whim and aim to avoid making changes that affect most existing machines. But we reserve the right to make _some_ behavior changes in minor releases. Our best judgment of the situation will always dictate such changes. Please always read our release notes before deciding to upgrade.

TypeScript changes


We also reserve a similar right to adjust declared TypeScript definitions or drop support for older versions of TypeScript in a minor release. The TypeScript language itself evolves quickly and often introduces breaking changes in its minor releases. Our team is also continuously learning how to leverage TypeScript more effectively - and the types improve as a result.

For these reasons, it is impractical for our team to be bound by decisions taken when an older version of TypeScript was its latest version or when we didn’t know how to declare our types in a better way. We won’t introduce declaration changes often - but we are more likely to do so than with runtime changes.

Packages


Most of the packages in the XState family declare a peer dependency on XState itself. We’ll be cautious about maintaining compatibility with already-released packages when releasing a new version of XState, but each release of packages depending on XState will always adjust the declared peer dependency range to include the latest version of XState. For example, you should always be able to update xstate without @xstate/react. But when you update @xstate/react, we highly recommend updating xstate too.