xstate
XState is a state management and orchestration library that uses finite state machines and statecharts to model complex application logic. Instead of managing s…
Installation
npm install xstate
yarn add xstate
pnpm add xstate
Import
import { createMachine, interpret } from 'xstate';Quick Example
import { createMachine, createActor } from 'xstate';
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: { on: { TOGGLE: 'active' } },
active: { on: { TOGGLE: 'inactive' } },
},
});
const actor = createActor(toggleMachine).start();
actor.send({ type: 'TOGGLE' }); // → 'active'About xstate
XState is a state management and orchestration library that uses finite state machines and statecharts to model complex application logic. Instead of managing state as arbitrary variables, XState defines explicit states (idle, loading, success, error), events that trigger transitions between states, and effects (actions, services) that execute during transitions. This approach makes impossible states impossible — if your machine is in the 'loading' state, it can only transition to 'success' or 'error', not back to 'loading'. XState provides createMachine for defining state machines, interpret/createActor for running them, and framework integrations (@xstate/react, @xstate/vue, @xstate/svelte) for using machines in UI components. Machines can spawn child actors for concurrent processes, use guards for conditional transitions, invoke promises and callbacks as services, and compose hierarchically through parallel and nested states. The XState Visualizer provides an interactive diagram of your machine's states and transitions, invaluable for understanding and documenting complex flows. XState is particularly effective for modeling multi-step forms, authentication flows, media players, complex UI interactions, and any scenario where the valid sequence of state transitions needs to be precisely defined and enforced.
Quick Facts
| Package | xstate |
| Category | State Management |
| Weekly Downloads | 1.5M+ |
| License | MIT |
| Install | npm install xstate |
Related Packages
Redux is a predictable state container for JavaScript applications, most commonly used with React bu…
Zustand is a small, fast, and scalable state management library for React that provides a simple hoo…
MobX is a battle-tested state management library that makes state management simple and scalable thr…
React is the most popular JavaScript library for building user interfaces, developed and maintained …
Browse npm Packages by Category
Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.