Design, implement, review, and migrate XState v5 state machines and statecharts in TypeScript using modern v5 patterns. Use this whenever the user mentions XState, actors, state machines, statecharts, guards, transitions, workflows, or Stately, or is modeling non-trivial UI/app/process logic in a codebase that uses XState. Prefer a short machine sketch before code when requirements are fuzzy. If the problem is too simple for a state machine, say so and recommend @xstate/store instead.
91%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Passed
No findings from the security scan
Use this reference when the task involves any of these:
assign(...)fromPromise(...) and fromCallback(...)assign(...)LLMs often act like assign(...) is the only useful action. It is not.
For typed reusable action logic, prefer setup-scoped helpers from a const machineSetup = setup(...) object when they make the behavior clearer:
machineSetup.createAction(...) for typed custom actionsmachineSetup.enqueueActions(...) when one transition should enqueue several actions conditionallymachineSetup.emit(...) when the machine should emit an event to the surrounding systemmachineSetup.assign(...), machineSetup.raise(...), machineSetup.sendTo(...), etc. when you want type-bound built-insMinimal pattern:
import { setup } from 'xstate';
const machineSetup = setup({
types: {} as {
context: { count: number };
events: { type: 'count.incremented'; value: number } | { type: 'count.flushed' };
emitted: { type: 'count.changed'; count: number };
}
});
const increment = machineSetup.assign({
count: ({ context, event }) =>
event.type === 'count.incremented' ? context.count + event.value : context.count
});
const raiseFlush = machineSetup.raise({ type: 'count.flushed' });
const emitChanged = machineSetup.emit(({ context }) => ({
type: 'count.changed',
count: context.count
}));
const flushIfNeeded = machineSetup.enqueueActions(({ context, enqueue }) => {
if (context.count > 10) {
enqueue(raiseFlush);
}
});Reference anchors:
enqueueActions(...) in a real machine: tiles machine exampleIf state A only stores data so state B can use it immediately, ask whether that data should just travel on an event.
Prefer:
Be careful about:
onDone or a later state can read themlatestChunk, callback payloads, or response wrappers when the machine only needs a derived durable value such as progressContext should hold durable state, not every hop in the protocol.
Do not default to fromPromise(...).
Prefer fromPromise(...) when:
onDone / onErrorPrefer fromCallback(...) when:
onDone / onError makes the machine awkwardWhen writing callback-actor examples:
msg, chunk, or err as implicit anyupload.progress or timer.ticked back to the parentReference anchors:
Minimal upload-style callback pattern:
import { assign, fromCallback, setup } from 'xstate';
type UploadMessage =
| { type: 'progress'; loaded: number; total: number }
| { type: 'complete' }
| { type: 'error'; error: unknown };
declare function startUploadAndListen(
uploadId: string,
onMessage: (message: UploadMessage) => void
): () => void;
const machineSetup = setup({
types: {} as {
context: {
uploadId: string | null;
progress: number;
error: string | null;
};
events:
| { type: 'upload.started'; uploadId: string }
| { type: 'upload.progress'; loaded: number; total: number }
| { type: 'upload.completed' }
| { type: 'upload.failed'; error: string };
},
actors: {
upload: fromCallback<
{ type: 'upload.progress'; loaded: number; total: number }
| { type: 'upload.completed' }
| { type: 'upload.failed'; error: string },
{ uploadId: string }
>(({ input, sendBack }) => {
return startUploadAndListen(input.uploadId, (message) => {
if (message.type === 'progress') {
sendBack({
type: 'upload.progress',
loaded: message.loaded,
total: message.total
});
return;
}
if (message.type === 'complete') {
sendBack({ type: 'upload.completed' });
return;
}
sendBack({ type: 'upload.failed', error: String(message.error) });
});
})
}
});
export const uploadMachine = machineSetup.createMachine({
context: {
uploadId: null,
progress: 0,
error: null
},
initial: 'idle',
states: {
idle: {
on: {
'upload.started': {
target: 'uploading',
actions: assign({ uploadId: ({ event }) => event.uploadId })
}
}
},
uploading: {
invoke: {
src: 'upload',
input: ({ context }) => ({ uploadId: context.uploadId! })
},
on: {
'upload.progress': {
actions: assign({
progress: ({ event }) =>
Math.round((event.loaded / event.total) * 100)
})
},
'upload.completed': { target: 'done' },
'upload.failed': {
target: 'failed',
actions: assign({ error: ({ event }) => event.error })
}
}
},
done: {},
failed: {}
}
});Machines can emit events. This is useful when the machine is driving a larger system and should announce something meaningful outward, instead of forcing every consumer to poll context or infer behavior indirectly.
Prefer emitted events when:
Use types.emitted plus machineSetup.emit(...) for typed emitted events.
Reference anchor:
machineSetup.emit(...): xstate core changelogLLMs often over-expand the statechart.
Prefer coarse parent states when:
Do not split aggressively just for conceptual purity. The goal is a sturdier model, not the maximum number of actors and states.
Prefer snapshot persistence over hand-rolled state reconstruction.
Canonical pattern:
import { createActor } from 'xstate';
import { authMachine } from './authMachine';
const persisted = loadPersistedSnapshot();
const actor = createActor(authMachine, {
snapshot: persisted
});
actor.subscribe(() => {
savePersistedSnapshot(actor.getPersistedSnapshot());
});In UI adapters, prefer provider or hook options that accept a persisted snapshot when available rather than rebuilding state manually.
Be careful about older examples that use state: in actor options. For current v5 code, prefer snapshot: when hydrating persisted machine state.
For migration or repair tasks, do not keep dead implementation override objects alive by passing them into useMachine(...) if the current hook does not accept them. Either move real implementations into setup(...)/machine config or remove dead overrides if they are unused.
Reference anchors:
snapshot hydration: createActorContext test