Imported from statelyai/skills (
skills/xstate-v5/SKILL.md) via skills.sh. Install upstream withnpx skills add statelyai/skills --skill xstate-v5. Copyright stays with the author.
XState v5
Use XState v5 APIs. In an existing codebase, check the installed version and read the nearby machines, actors, stores, and adapter usage. Use the official v5 docs when local examples use legacy APIs.
Task mode
Choose a mode before writing code:
- New code: prefer the modern v5 patterns in this skill.
- Local edit: preserve local structure and naming unless the current code is mixed, broken, or cleanup was requested.
- Migration: prefer the smallest safe translation to v5. Preserve structure and semantics unless broader normalization was requested.
For migration and local edits, do not introduce setup(...), named implementations, object-form guards/actions, tags, or actor decomposition unless they are required for correctness, significantly reduce local complexity, or were explicitly requested.
Choose the tool
Prefer @xstate/store when the domain is simple event-based state management:
- no meaningful finite modes that need coordination, orchestration, or explicit lifecycle modeling
- no invoked async processes
- no actor communication
- no need for state machine or statechart concepts such as guarded transitions, delayed transitions, parallel states, or history
Simple fetching or mutation logic can still fit @xstate/store if it does not need machine-level orchestration.
Prefer XState when the domain has one or more of these:
- finite modes that matter to behavior or UI
- async workflows, retries, cancellation, or background processes
- multiple interacting processes or child actors
- explicit guards, delays, tags, or transition rules
- a need to model business process flow, not just update state
If the problem is too simple for a machine, say so plainly and recommend @xstate/store.
Design and implement
- Name the modes, domain events, guards, and side effects. Sketch the transitions when requirements are unclear.
- Keep modes in states and durable data in context. Compute derived values in functions or selectors. Carry one-step data in event payloads.
- Choose a guard for a condition and a state for a mode with its own behavior. Give child actors independent lifecycles or internal steps that the parent does not need to manage.
- Implement the transition that owns each update. Use invoked actors for processes tied to a state's lifetime and actions for transition effects. Consider emitted events when consumers need a direct notification.
Example
An editor begins closed, accepts editor.opened, and returns to closed
on editor.closed. Use the actor snapshot to check the current mode.
import assert from 'node:assert/strict';
import { createActor, setup } from 'xstate';
const editor = setup({
types: {
events: {} as { type: 'editor.opened' } | { type: 'editor.closed' },
},
}).createMachine({
initial: 'closed',
states: {
closed: { on: { 'editor.opened': { target: 'open' } } },
open: { on: { 'editor.closed': { target: 'closed' } } },
},
});
const actor = createActor(editor).start();
assert.equal(actor.getSnapshot().can({ type: 'editor.closed' }), false);
actor.send({ type: 'editor.opened' });
assert.equal(actor.getSnapshot().matches('open'), true);
actor.send({ type: 'editor.closed' });
assert.equal(actor.getSnapshot().matches('closed'), true);
actor.stop();
Preferred v5 patterns
For new code, prefer these patterns unless the local codebase has a strong reason not to:
- TypeScript only.
- Prefer
setup({...}).createMachine({...}). - Define named
actions,guards,actors, anddelaysinsetup(...). - Prefer transition objects like
{ target: 'next' }over shorthand when it improves consistency. - Prefer arrays for
actions, even for a single action, when that keeps the shape consistent. - Prefer action and guard objects such as
{ type: 'track' }or{ type: 'isValid', params: ... }when the intent is reusable or named. - Prefer
tags: []for UI semantics and cross-cutting state meaning. - In a parallel state, place a transition on the substate or region whose
lifecycle needs to change. Check region-root transitions that target a
sibling region or use
reenter: true. They can reset the source region to its initial substate and cancel active invokes. - Prefer passing data into named actions and guards via
paramsinstead of reaching intoeventdirectly. - Do not treat
assign(...)as the only action pattern. For typed reusable logic beyond simple context updates, consider setup-scoped helpers from aconst machineSetup = setup(...)object, such asmachineSetup.createAction(...),machineSetup.enqueueActions(...), andmachineSetup.emit(...), or named action objects when they fit the behavior better. - Use one
paramstype across the property updaters in a namedassign(...). Split the assigners if their parameters differ. - When an implementation must inspect
eventand the type is not obvious, preferassertEvent(...)for narrowing. - Avoid
as anyand other loose casts in examples and final code unless there is no cleaner local option. - Choose actor logic intentionally: prefer
fromPromise(...)for one request/one result, and preferfromCallback(...)for subscriptions, timers, external callbacks, and multi-event protocols that send events back over time. - Consider
emit(...)when the machine should notify the surrounding system directly.
Use domain events and follow local naming conventions. Dot-separated names
can group related events for partial event descriptors.
See TypeScript narrowing for assertEvent(...).
See references/examples.md for canonical code shapes, references/advanced-patterns.md when the task involves typed actions beyond assign(...), callback actors, emitted events, or persistence/hydration, and references/observables-and-inspection.md for fromObservable(...), inspection, and browser inspector patterns.
UI integration
Prefer letting the machine drive UI behavior:
- use
snapshot.matches(...)for finite mode checks - use tags for semantic checks such as loading, saving, or dirty
- use
snapshot.can(...)to drive whether an event is currently valid
If a component owns a small local actor, useMachine(...) is often enough.
If an actor is shared, long-lived, or performance-sensitive:
- create or obtain an actor ref once
- read slices with
useSelector(...) - use actor context/provider helpers when the actor is shared across a subtree
See references/adapters.md for concise adapter guidance.
Review and repair
Trace one expected event sequence and the sequence that exposes the bug. Check mode ownership, actor lifecycles, and whether effects run in the correct place. Apply the v5 patterns above to the code under review. In parallel regions, check which state exits and whether any invoke restarts.
Migration
When legacy code is present, translate toward v5 gradually and locally unless the user asked for a broader migration.
Common migration targets include:
cond->guardschema->typesservices->actorsinterpret(...)->createActor(...)- old function signatures -> destructured v5 arguments such as
({ context, event })
For migration tasks:
- preserve local structure first
- change only what is needed for correctness, compatibility, or clarity
- do not normalize into the full preferred house style unless the user asked for that
- explain any non-local refactor you choose to make
- do not preserve dead or invalid hook option patterns just because they existed nearby
- when migrating React usage, prefer valid current hook surfaces over trying to smuggle old
interpret-style implementation overrides intouseMachine(...) - apply the parallel transition rules above when migrating v4 regions
Use references/v4-to-v5-quick-ref.md for quick translation patterns.
Persistence
When persistence or hydration matters:
- persist snapshots, not just context, unless context-only restore is truly sufficient
- prefer
actor.getPersistedSnapshot()for saving machine state - prefer hydrating with
createActor(machine, { snapshot })or adapter/provider snapshot options where available - do not hand-roll restoration by guessing the state value plus a partial context blob
See references/advanced-patterns.md for concrete persistence and hydration patterns.
Verify behavior
Type-check changed code and run the relevant existing tests. If the flow has no focused test, start an actor, send the affected events, and inspect the resulting snapshots. Include a rejected event or failure path when the change affects one. If a check fails, trace the first unexpected snapshot back to its transition, guard, or invoke, correct it, and rerun the same check. Report which checks you ran.
When asked to write tests, assert transitions, guards, and actor outcomes. For UI tests, check the behavior users can observe. See XState testing and path generation.
Optional tools
Stately Studio and inspection tools can help with design, debugging, and communication, but they are optional. Mention them when the user is designing a machine, wants visualization, or needs better debugging visibility.
- Stately Studio for visual modeling and collaboration
- Inspection API for observing actor systems
- Stately Inspector for visual inspection in running apps
Output format
Prefer this output shape:
- Short machine sketch if requirements are fuzzy.
- Code.
- Brief rationale explaining states, events, context, actors, and tags.
- Migration notes only if relevant.
Keep examples runnable. Include real imports, typed event objects, and any
referenced helpers. For invoked work, check the actor and invoke.input shape.
If the example needs unrelated files, reduce it to the code that demonstrates
the behavior.
