Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问clear审计通过

react-state-machinesReact state machines 前端

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

3,819

周安装

156

GitHub Stars

39

下载量

1,236
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:react-state-machines(React state machines 前端)
来源仓库:https://github.com/bobmatnyc/claude-mpm-skills
仓库路径:skills/react-state-machines
安装命令:
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill react-state-machines
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill react-state-machines

简介

辅助 React 状态机模式开发与复杂交互管理。

  • 适用于生成或审查基于 XState 等库的状态驱动代码。
  • 可整理状态流转、事件处理与副作用管理逻辑。
  • 需结合项目业务逻辑与状态复杂度谨慎使用。react-state-machines 属于前端设计类 Skill,可作为该场景下的辅助能力补充。
  • 建议在关键交互流程上配合人工建模与测试覆盖。

SKILL.md

React State Machines with XState v5

Overview

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.

When to Use This Skill

Trigger patterns:

  • Boolean flag explosion: multiple isLoading, isError, isSuccess flags
  • Implicit states: writing if (isLoading &&!isError && data) to derive mode
  • Defensive coding: guards before state updates to prevent invalid transitions
  • Timing coordination: timeouts, delays, debouncing across states
  • State dependencies: one state depends on another to update correctly

Do not use for:

  • Simple boolean toggles with no async (useState is simpler)
  • Single form fields with basic validation (useReducer suffices)
  • Server state caching (React Query/TanStack Query handles this)
  • Static data transformations (useMemo is better)
  • Simple counters or toggles (useState is clearer)

See decision-trees.md for comprehensive decision guidance

Core Mental Model

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.

Quick Start: XState v5 setup() Pattern

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' } }
  }
});

React Integration Decision Tree

Use CaseHookWhy
Simple component stateuseMachineStraightforward, re-renders on all changes
Performance-criticaluseActorRef + useSelectorSelective re-renders only
Global/shared statecreateActorContextReact 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
}

Anti-Patterns to Avoid

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));

Navigation to References

Core Patterns

  • xstate-v5-patterns.md: Complete v5 API, statecharts (hierarchy/parallel/history), promise actors
  • react-integration.md: useMachine vs useActorRef, Context patterns, side effect handling
  • testing-patterns.md: Unit testing, mocking actors, visualization debugging

Decision Making & Best Practices

  • decision-trees.md: When to use state machines vs useState/useReducer/React Query, machine splitting strategies
  • real-world-patterns.md: Complete examples - auth flows, file uploads, wizards, undo/redo, shopping carts
  • error-handling.md: Error boundaries, retry strategies, circuit breakers, graceful degradation
  • performance.md: Selector memoization, React.memo integration, machine splitting for performance

Advanced Topics

  • persistence-hydration.md: localStorage persistence, SSR/Next.js hydration, snapshot serialization
  • migration-guide.md: Step-by-step migration from useState/useReducer with before/after examples
  • composition-patterns.md: Actor communication, machine composition, higher-order machines, systemId
  • skills-architecture.md: Input/output parameterization, library structure

Key Reminders

  1. setup() is the v5 way: Strong TypeScript inference, actor registration, action definitions
  2. Invoke for async, actions for sync: Actions are fire-and-forget; invoked actors have lifecycle
  3. Finite states for modes, context for data: Don't create states for every data variation
  4. Visualize first: Stately Studio (stately.ai/editor) makes machines living documentation

Red Flags

  • More than 3-4 boolean flags → Need state machine
  • Writing if (a &&!b && c) to determine mode → States should be explicit
  • Bugs from invalid state combinations → Machine prevents impossible states
  • Can't explain state transitions to stakeholders → Visualization solves this

Related Skills

  • react: Parent skill for React patterns
  • nextjs: Server/client state coordination
  • test-driven-development: Test machines with createActor before UI integration

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

28.38%
按下载量换算351

Antigravity

23.63%
按下载量换算292

OpenCode

17.9%
按下载量换算221

Gemini CLI

14.42%
按下载量换算178

github-copilot

8.27%
按下载量换算102

Cursor

3.63%
按下载量换算45

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills