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 orchestration.
What this skill does
# 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:
```typescript
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:
```typescript
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:
```typescript
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
```typescript
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
```typescript
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 subscriptions:
```typescript
import { fromCallback } from "xstate";
import { QueryObserver, type QueryClient } from "@tanstack/react-query";
const subscribeToQuery = fromCallback(({ input, sendBack }) => {
const { queryClient, entityId } = input as {
queryClient: QueryClient;
entityId: string;
};
const observer = new QueryObserver(queryClient, {
queryKey: ["data", entityId],
queryFn: async () => { /* fetch logic */ },
});
const unsubscribe = observer.subscribe((result) => {
if (result.data) {
sendBack({ type: "REMOTE_UPDATE", data: result.data });
}
});
// Emit current result immediately
const currentResult = observer.getCurrentResult();
if (currentResult.data) {
sendBack({ type: "REMOTE_UPDATE", data: currentResult.data });
}
return () => unsubscribe();
});
```
### Mutations with useMutation
Wrap `useMutation` hooks as `fromPromise` actors and provide via `.provide()`:
```typescript
const machine = useMemo(
() =>
createDataMachine().provide({
actors: {
saveData: fromPromise(async ({ input }) => {
return await saveMutation.mutateAsync(input.data);
}),
},
}),
[saveMutation]
);
```
**For detailed patterns**: See `references/query-patterns.md`
---
## Essential Patterns (All Tools)
1. **Use `setup()` for all machines** - provides superior type inference
2. **Use enums for event types** - UPPER_SNAKE_CASE convention
3. **Define actions outside `setup()`** - use type-bound helpers like `setup().assign()`
4. **Use `enqueueActions()` for sequential actions** - group related actions together
5. **Use `.provide()` for React integration** - override actions with external methods
6. **Initialize context from `input`** - use function form for dynamic initialization
7. **Always spread `...context` in stores** - preserve other properties
8. **Clean up subscriptions** - return cleanup functions from callback actors
---
## When to Use Each Tool
### Use XState State Machines When:
- Need finite states with specific transitions
- Need guards and conditional transition logic
- Need invoked actors for async orchestration
- Need hierarchical or parallel states
- Building complex multi-step workflows
### Use @xstate/store When:
- Simple global or local state management
- Event-driven state updates without complex flows
- Need undo/Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.