ScriptsApr 11, 2026·1 min read

XState — State Machines & Statecharts for Complex Logic

XState is a library for creating, interpreting, and executing finite state machines and statecharts. Model complex application logic declaratively with first-class TypeScript, React/Vue/Svelte bindings, and visual editor (Stately).

SC
Script Depot · Community
Quick Use

Use it first, then decide how deep to go

This block should tell both the user and the agent what to copy, install, and apply first.

npm i xstate @xstate/react
import { setup } from "xstate";
import { useMachine } from "@xstate/react";

const toggleMachine = setup({}).createMachine({
  id: "toggle",
  initial: "inactive",
  states: {
    inactive: { on: { TOGGLE: "active" } },
    active: { on: { TOGGLE: "inactive" } },
  },
});

function Toggle() {
  const [state, send] = useMachine(toggleMachine);
  return (
    <button onClick={() => send({ type: "TOGGLE" })}>
      {state.value}
    </button>
  );
}
Intro

XState is a library for creating, interpreting, and executing finite state machines and statecharts. Built by David Khourshid and the Stately team, it brings rigorous state modeling (SCXML-inspired) to JavaScript with full TypeScript support and a visual editor.

What XState Does

  • Finite state machines — explicit states and transitions
  • Statecharts — hierarchical, parallel, history states
  • Actors — async, message-passing concurrency model
  • Visualizer — Stately Studio for drag-and-drop editing
  • Guards & actions — conditional transitions and side-effects
  • Delayed transitions — timeouts without setTimeout juggling
  • Model-based testing — auto-generate tests from machines

Architecture

A machine is a pure object describing states, events, transitions, and effects. createActor(machine) spawns a running instance. Actors can spawn child actors, creating a hierarchy. Works in any JS runtime; bindings exist for React, Vue, Svelte, Solid.

Self-Hosting

Client-side library. Stately Studio is a SaaS for visual editing (optional), but machines run anywhere.

Key Features

  • Statecharts with hierarchy & parallel states
  • Actor model for concurrency
  • Fully type-safe (v5 uses setup() for inference)
  • Visual editor (Stately Studio)
  • Test generator (@xstate/test)
  • Framework-agnostic core
  • Bindings for React, Vue, Svelte, Solid
  • SCXML export

Comparison

Library Paradigm Complexity Visual Tools
XState Statecharts Highest ceiling Stately Studio
Zustand Hooks store Low No
Redux Reducers Medium Redux DevTools
MobX Reactive Medium MobX DevTools

常见问题 FAQ

Q: 什么时候用 XState? A: 复杂 UI 流程(多步表单、付款流程、视频播放器、协作编辑)。简单全局状态用 Zustand 就够了。

Q: Actor 模型是什么? A: 并发模型:每个 actor 是独立状态机,通过消息通信。避免共享状态带来的竞态。

Q: v5 有什么变化? A: v5 引入 setup() API 实现更好的 TS 类型推断、简化 actor 系统、移除 interpret 改用 createActor。

来源与致谢 Sources

Discussion

Sign in to join the discussion.
No comments yet. Be the first to share your thoughts.

Related Assets