一键导入
react-state-machine
Building reusable React state machine skills with XState v5 and the actor model
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Building reusable React state machine skills with XState v5 and the actor model
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
ONNX Runtime in Rust via the `ort` crate (2.x): loading sessions, configuring CPU/CoreML/CUDA execution providers, tensor I/O with ndarray, async-safe spawn_blocking wrapping, global thread-pool init, and debugging provider/opset issues
Modern React 19 platform features and rendering architecture - the React Compiler (auto-memoization) and how it changes memoization guidance, concurrent rendering (useTransition/useDeferredValue/Suspense), the use() hook, Actions (useActionState/useOptimistic/useFormStatus), ref-as-prop and Context-as-provider changes, compound components, context selectors, error boundaries, portals, virtualization, code-splitting, and the RSC/'use client' boundary.
General React fundamentals - components and JSX, props and state, the core hooks (useState/useEffect/useRef/useMemo/useCallback/useContext), composition, conditional and list rendering, and controlled inputs. The canonical "depends on React" reference.
Advanced React hooks composition patterns - SWR integration, debounced search, memoized contexts, state machines, and performance optimization
Vite lightning-fast build tool with instant HMR, ESM-first architecture, and zero-config setup for modern web development
Production-ready Express.js development covering middleware architecture, error handling, security hardening, testing strategies, and deployment patterns
| name | react-state-machine |
| description | Building reusable React state machine skills with XState v5 and the actor model |
| user-invocable | false |
| disable-model-invocation | true |
| version | 1.0.1 |
| category | development |
| author | Claude MPM Team |
| license | MIT |
| progressive_disclosure | {"entry_point":{"summary":"Build type-safe, visualizable React state machines using XState v5's actor model for predictable UI behavior","when_to_use":"Complex async flows, multi-step forms, modal animations, media players, boolean flag explosion, defensive coding patterns","quick_start":"1. Define states/events with setup() 2. Use promise actors for async 3. useMachine for simple, useActorRef+useSelector for performance 4. Test with createActor 5. Visualize in Stately Studio"},"references":["xstate-v5-patterns.md","react-integration.md","skills-architecture.md","testing-patterns.md","decision-trees.md","real-world-patterns.md","error-handling.md","performance.md","persistence-hydration.md","migration-guide.md","composition-patterns.md"]} |
| context_limit | 700 |
| tags | ["react","state-machine","xstate","actors","async","forms","ui-logic"] |
| requires_tools | [] |
State machines make impossible states unrepresentable by modeling UI behavior as explicit states, transitions, and events. XState v5 (2.5M+ weekly npm downloads) unifies state machines with the actor model—every machine is an independent entity with its own lifecycle, enabling sophisticated composition patterns.
Trigger patterns:
isLoading, isError, isSuccess flagsif (isLoading && !isError && data) to derive modeDo not use for:
See decision-trees.md for comprehensive decision guidance
Finite states represent modes of behavior: idle, loading, success, error. A component can only be in ONE state at a time.
Context (extended state) stores quantitative data that doesn't define distinct states. The finite state says "playing"; context says what at what volume.
Events trigger transitions between states. Events are objects: { type: 'SUBMIT', data: formData }.
Guards conditionally allow/block transitions: { guard: 'hasValidInput' }.
Actions are fire-and-forget side effects during transitions or state entry/exit.
Invoked actors are long-running processes (API calls, subscriptions) with lifecycle management and cleanup.
import { setup, assign, fromPromise } from 'xstate';
const fetchMachine = setup({
types: {
context: {} as { data: User | null; error: string | null },
events: {} as
| { type: 'FETCH'; userId: string }
| { type: 'RETRY' }
},
actors: {
fetchUser: fromPromise(async ({ input, signal }) => {
const res = await fetch(`/api/users/${input.userId}`, { signal });
if (!res.ok) throw new Error(res.statusText);
return res.json();
})
},
actions: {
setData: assign({ data: ({ event }) => event.output }),
setError: assign({ error: ({ event }) => event.error.message })
}
}).createMachine({
id: 'fetch',
initial: 'idle',
context: { data: null, error: null },
states: {
idle: { on: { FETCH: 'loading' } },
loading: {
invoke: {
src: 'fetchUser',
input: ({ event }) => ({ userId: event.userId }),
onDone: { target: 'success', actions: 'setData' },
onError: { target: 'failure', actions: 'setError' }
}
},
success: { on: { FETCH: 'loading' } },
failure: { on: { RETRY: 'loading' } }
}
});
| Use Case | Hook | Why |
|---|---|---|
| Simple component state | useMachine | Straightforward, re-renders on all changes |
| Performance-critical | useActorRef + useSelector | Selective re-renders only |
| Global/shared state | createActorContext | React Context integration |
Basic pattern:
import { useMachine } from '@xstate/react';
function Toggle() {
const [snapshot, send] = useMachine(toggleMachine);
return (
<button onClick={() => send({ type: 'TOGGLE' })}>
{snapshot.matches('inactive') ? 'Off' : 'On'}
</button>
);
}
Performance pattern:
import { useActorRef, useSelector } from '@xstate/react';
const selectCount = (s) => s.context.count;
const selectLoading = (s) => s.matches('loading');
function Counter() {
const actorRef = useActorRef(counterMachine);
const count = useSelector(actorRef, selectCount);
const loading = useSelector(actorRef, selectLoading);
// Only re-renders when count or loading changes
}
❌ State explosion: Flat states for orthogonal concerns. Use parallel states instead.
❌ Sending events from actions: Never send() inside assign. Use raise for internal events.
❌ Impure guards: Guards must be pure—no side effects, no external mutations.
❌ Subscribing to entire state: Use focused selectors with useSelector.
❌ Not memoizing model:
// WRONG
const model = Model.fromJson(layout); // New model every render
// CORRECT
const modelRef = useRef(Model.fromJson(layout));
if (a && !b && c) to determine mode → States should be explicit