React State Machine logo

React State Machine

Community
bobmatnyc
react-state-machine

Building reusable React state machine skills with XState v5 and the actor model

Overview

Publisherbobmatnyc
Repositoryclaude-mpm-skills
Skill namereact-state-machine
Stars
75
Forks
19
Bundled files
12
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 12 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by bobmatnyc on GitHub. Read the source before you install it.

Installation

Install the React State Machine AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/bobmatnyc/claude-mpm-skills.git /tmp/claude-mpm-skills
mkdir -p .claude/skills
cp -r /tmp/claude-mpm-skills/toolchains/javascript/frameworks/react/react-state-machine .claude/skills/react-state-machine
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable React State Machine in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads React State Machine on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so React State Machine is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

typescript
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:

typescript
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:

typescript
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:

typescript
// 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

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the React State Machine AI skill do?

Building reusable React state machine skills with XState v5 and the actor model

Why use React State Machine on TypingMind?

Because you install it once and use it with any model. React State Machine is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install React State Machine in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/bobmatnyc/claude-mpm-skills/tree/main/toolchains/javascript/frameworks/react/react-state-machine. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use React State Machine?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with React State Machine?

As many as you like. As long as a model supports skills, you can use React State Machine with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the React State Machine AI skill free?

Yes. It is published on GitHub by bobmatnyc under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇