# 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). ## Install Save as a script file and run: ## Quick Use ```bash npm i xstate @xstate/react ``` ```ts 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 ( ); } ``` ## 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. - **Repo**: https://github.com/statelyai/xstate - **Stars**: 29K+ - **Language**: TypeScript - **License**: MIT ## 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 - Docs: https://stately.ai/docs - GitHub: https://github.com/statelyai/xstate - License: MIT --- Source: https://tokrepo.com/en/workflows/2f0e099f-3567-11f1-9bc6-00163e2b0d79 Author: Script Depot