State Machines
Modeling complex UI / workflow state with finite state machines and statecharts.
When useState and conditionals start producing impossible states ("loading and error?", "submitted but still editable?"), reach for a state machine.
Libraries
- ★ XState v5 — TypeScript-first, statecharts (hierarchical / parallel states), actors, invocations. The default in 2026. Pairs with React, Vue, Svelte, Solid, vanilla.
@xstate/store— minimal store with optional state-machine semantics; great middle ground if XState's full API is overkill.- Zag — primitive state machines for UI components; powers Ark UI and Chakra v3 internally. You'll consume it indirectly.
- Robot — small finite state machines (~1KB).
- Stately Studio — XState's visual editor; cloud-hosted; can sync with code.
- Effect Machine (Effect-TS) — state machines as part of the Effect ecosystem.
Workflow / orchestration (server-side, not just UI)
For long-running, multi-step, durable workflows see Workflow Engines.
When to reach for a state machine
- Multi-step forms / wizards.
- Auth flows (signed-out → email → OTP → 2FA → signed-in).
- Onboarding with branching.
- Anything with "now we're loading, but I just clicked again, and there's an error from earlier."
- Realtime UIs with multiple peers / sources of truth.
- Animations sequenced through specific phases.
When not to
- Simple toggles / single-loading-state.
- CRUD pages where TanStack Query already manages state.
- Truly throwaway prototypes.
Patterns to know
- Statecharts > FSMs for non-trivial UIs (hierarchical, parallel, history states).
- Actor model — each long-running process is its own machine; they message each other.
- Visualize first — drawing the diagram in Stately or Mermaid often catches missing transitions before you write code.
Pick this if…
- Default complex UI state machine: XState v5.
- Lighter touch, just need a store with finite-state vibes:
@xstate/store. - Tiny FSM: Robot.
- Building a UI primitive: Zag (you'll use it via Ark / Chakra).
- You want a visual editor: Stately Studio.