Implement XState v5 state machines with strict patterns — setup().createMachine(), actors, and TypeScript typing. Triggers: "create state machine", "implement XState", "design statechart", "add actor", XState, statecharts, fromPromise.
tsc --version 2>/dev/null || echo "NOT INSTALLED"XState v5 ONLY. Requires TypeScript 5.0+. Never use v4 patterns.
types.context, types.events, types.input (+ types.output)setup({...}).createMachine({...}) with all implementations in setuptsc --noEmit, no any leaks, no string events, no v4 importsimport { setup, assign, fromPromise, createActor } from "xstate"
const machine = setup({
types: {
context: {} as { count: number },
events: {} as { type: "inc" } | { type: "add"; amount: number },
input: {} as { initialCount?: number },
},
actions: {
inc: assign({ count: ({ context }) => context.count + 1 }),
add: assign({
count: ({ context }, params: { amount: number }) => context.count + params.amount,
}),
},
guards: {
isPositive: ({ context }) => context.count > 0,
},
}).createMachine({
id: "counter",
context: ({ input }) => ({ count: input.initialCount ?? 0 }),
initial: "active",
states: {
active: {
on: {
inc: { actions: "inc" },
add: {
actions: {
type: "add",
params: ({ event }) => ({ amount: event.amount }),
},
},
},
},
},
})
const actor = createActor(machine, { input: { initialCount: 0 } })
actor.subscribe((snapshot) => console.log(snapshot.context.count))
actor.start()
actor.send({ type: "inc" })
setup({...}).createMachine({...}) for all machinessetup(): actions, guards, actors(_, params: { ... }) second argactor.send({ type: "X" }), never stringsinvoke has onError: always handle failureinterpret, Machine, cond, send, pure, choose| v4 (WRONG) | v5 (CORRECT) |
|---|---|
createMachine() alone | setup().createMachine() |
interpret() | createActor() |
services: {} | actors: {} |
cond | guard |
send() action | raise() or sendTo() |
pure()/choose() | enqueueActions() |
withContext() | input |
withConfig() | provide() |
spawn import | spawnChild or ({ spawn }) args |
| Type | Creator | Use Case |
|---|---|---|
| State Machine | setup().createMachine() | Complex state logic |
| Promise | fromPromise() | Async request/response |
| Callback | fromCallback() | Bidirectional streams, SDK bridging |
| Observable | fromObservable() | RxJS streams |
| Transition | fromTransition() | Reducer-like state |
sendToBefore writing machine code, produce:
from -> on event -> guard? -> actions -> to