Skip to content
AI & Agents
Skill

/xstate

Comprehensive guide for XState v5 ecosystem including state machines, actors, @xstate/store, and TanStack Query integration. Use when implementing state machines, event-driven stores, client state management, or integrating XState with React and TanStack Query for data fetching

BOOST
From plugin
pedronauck-skills
63787 skills1 command
Install
$ npx -y skills add pedronauck/skills --skill xstate --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/xstate

Context preview

The summary Claude sees to decide when to auto-load this skill.

Comprehensive guide for XState v5 ecosystem including state machines, actors, @xstate/store, and TanStack Query integration. Use when implementing state machines, event-driven stores, client state management, or integrating XState with React and TanStack Query for data fetching

SKILL.md

xstate.SKILL.md
name: xstate
description: Comprehensive guide for XState v5 ecosystem including state machines, actors, @xstate/store, and TanStack Query integration. Use when implementing state machines, event-driven stores, client state management, or integrating XState with React and TanStack Query for data fetching orchestration.
allowed-tools: Read, Grep, Glob

XState v5 Developer Guide

This skill provides comprehensive guidelines, patterns, and best practices for working with the XState v5 ecosystem in this project, including:

  • **XState State Machines** - Finite state machines and actors for complex application logic
  • **@xstate/store** - Simple event-driven stores for lightweight state management
  • **XState + TanStack Query** - Integration patterns for data fetching orchestration

Quick Reference

| Use Case | Tool | Reference | |----------|------|-----------| | Complex state flows, guards, hierarchical states | XState Machines | `references/machine-patterns.md` | | Simple event-driven state, atoms, undo/redo | @xstate/store | `references/store-patterns.md` | | Data fetching with state orchestration | XState + TanStack Query | `references/query-patterns.md` |

Core Principles

XState State Machines

  • **Explicit States**: Model application logic as explicit finite states and events
  • **Actor Model**: Embrace the actor model for complex orchestration
  • **Impossible States**: Use statecharts to eliminate impossible states
  • **Declarative Thinking**: Think declaratively about state transitions
  • **Visualization**: Use Stately Editor for visual machine creation and debugging

@xstate/store

  • **Event-Driven Updates**: Use events for all state updates (never direct mutations)
  • **Keep Stores Simple**: Focus on data management, not complex logic
  • **Optimized Subscriptions**: Leverage selectors for efficient state access
  • **Reactive State**: Use atoms for composable, reactive state
  • **Upgrade Path**: Migrate to XState machines when complexity grows

XState + TanStack Query Integration

  • **XState for Orchestration**: Use XState machines for workflow orchestration
  • **TanStack Query for Data**: Use TanStack Query for data fetching and caching
  • **Actors as Bridges**: Wrap Query operations as XState actors
  • **Cache Updates in Mutations**: Keep query cache updates in mutation callbacks

---

XState State Machines

Creating a Machine with setup() API

Always use the `setup()` API for type-safe machines:

import { setup, createActor } from 'xstate';

export enum CounterEventType {
  INCREMENT = 'increment',
  DECREMENT = 'decrement',
}

const counterMachineSetup = setup({
  types: {
    context: {} as { count: number },
    events: {} as
      | { type: CounterEventType.INCREMENT }
      | { type: CounterEventType.DECREMENT },
    input: {} as { initialCount: number },
  },
  guards: {
    isPositive: ({ context }) => context.count > 0,
  },
});

// Define actions OUTSIDE setup using type-bound helpers
const incrementCount = counterMachineSetup.assign({
  count: ({ context }) => context.count + 1,
});

export const counterMachine = counterMachineSetup.createMachine({
  id: 'counter',
  context: ({ input }) => ({ count: input.initialCount }),
  initial: 'active',
  states: {
    active: {
      on: {
        [CounterEventType.INCREMENT]: {
          actions: incrementCount,
        },
      },
    },
  },
});

React Integration

Use `useMachine()` for component-scoped machines and `.provide()` for action overrides:

import { useMachine } from '@xstate/react';
import { useMemo } from 'react';

function Counter({ onExternalAction }) {
  const machine = useMemo(
    () =>
      counterMachine.provide({
        actions: {
          logEvent: () => onExternalAction(),
        },
      }),
    [onExternalAction]
  );

  const [state, send] = useMachine(machine);

  return (
    <button onClick={() => send({ type: CounterEventType.INCREMENT })}>
      Count: {state.context.count}
    </button>
  );
}

**For detailed patterns**: See `references/machine-patterns.md`

---

@xstate/store

Creating a Store

Define stores with clear initial context and event-based transitions:

import { createStore } from '@xstate/store';

const userStore = createStore({
  context: {
    user: null as { id: string; name: string } | null,
    isLoading: false,
    error: null as string | null,
  },
  on: {
    setUser: (context, event: { user: { id: string; name: string } }) => ({
      ...context, // Always spread to preserve other properties
      user: event.user,
      error: null,
    }),
    setLoading: (context, event: { isLoading: boolean }) => ({
      ...context,
      isLoading: event.isLoading,
    }),
  },
});

// Use the trigger API for type-safe event sending
userStore.trigger.setUser({ user: { id: '1', name: 'John' } });

React Integration

import { useSelector, useStore } from '@xstate/store/react';

function Counter() {
  const store = useStore({
    context: { count: 0 },
    on: {
      increment: (context, event: { by: number }) => ({
        ...context,
        count: context.count + event.by,
      }),
    },
  });
  const count = useSelector(store, (state) => state.context.count);
  return <button onClick={() => store.trigger.increment({ by: 1 })}>{count}</button>;
}

Undo/Redo Pattern

import { createStore } from '@xstate/store';
import { undoRedo } from '@xstate/store/undo';

const editorStore = createStore(
  undoRedo({
    context: { text: '' },
    on: {
      insertText: (context, event: { text: string }) => ({
        ...context,
        text: context.text + event.text,
      }),
    },
  })
);

editorStore.trigger.undo();
editorStore.trigger.redo();

**For detailed patterns**: See `references/store-patterns.md`

---

XState + TanStack Query Integration

Query Subscriptions with QueryObserver

Use `fromCallback` with `QueryObserver` for reactive subscriptio

Read more
Ships withpedronauck-skills

A curated collection of 87 agent skills for Claude Code and compatible AI coding assistants — 40 original (⭐️), 34 hand-picked (💎), and 13 marketing & business (📣).

Get the whole plugin
Stats
637
Stars
89
Forks
Maintained
Maintenance
Python
Language
1mo ago
Last commit
7mo ago
Created
4h ago
Added

Repo: pedronauck/skills

Other skills on pedronauck-skills.