react-state-flows
Complex multi-step operations in React. Use when implementing flows with multiple async steps, state machine patterns, or debugging flow ordering issues. Works for both React web and React Native.
Best use case
react-state-flows is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Complex multi-step operations in React. Use when implementing flows with multiple async steps, state machine patterns, or debugging flow ordering issues. Works for both React web and React Native.
Teams using react-state-flows should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/react-state-flows/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How react-state-flows Compares
| Feature / Agent | react-state-flows | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Complex multi-step operations in React. Use when implementing flows with multiple async steps, state machine patterns, or debugging flow ordering issues. Works for both React web and React Native.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Complex State Flows
## Problem Statement
Multi-step operations with dependencies between steps are prone to ordering bugs, missing preconditions, and untested edge cases. Even without a formal state machine library, thinking in states and transitions prevents bugs.
---
## Pattern: State Machine Thinking
**Problem:** Complex flows have implicit states that aren't modeled, leading to invalid transitions.
**Example - Checkout flow states:**
```
IDLE → VALIDATING → PROCESSING_PAYMENT → CONFIRMING → COMPLETE
↓
ERROR
```
**Each transition should have:**
1. **Preconditions** - What must be true before this step
2. **Action** - What happens during this step
3. **Postconditions** - What must be true after this step
4. **Error handling** - What to do if this step fails
```typescript
// Document the flow explicitly
/*
* CHECKOUT FLOW
*
* State: IDLE
* Precondition: cart exists with items
* Action: validateCart
* Postcondition: cart validated, prices confirmed
*
* State: VALIDATING
* Precondition: cart validated
* Action: processPayment
* Postcondition: payment authorized
*
* State: PROCESSING_PAYMENT
* Precondition: payment authorized
* Action: confirmOrder
* Postcondition: order created, confirmation number assigned
*
* ... continue for each state
*/
```
---
## Pattern: Explicit Flow Implementation
**Problem:** Flow logic scattered across multiple functions, hard to verify ordering.
```typescript
// WRONG - implicit flow, easy to miss steps or misordering
async function checkout(cartId: string) {
validateCart(cartId); // Missing await!
await processPayment(cartId);
await confirmOrder(cartId);
}
// CORRECT - explicit flow with validation
async function checkout(cartId: string) {
const flowId = `checkout-${Date.now()}`;
logger.info(`[${flowId}] Starting checkout flow`, { cartId });
// Step 1: Validate cart
await validateCart(cartId);
const cart = useStore.getState().cart;
if (!cart.validated) {
throw new Error(`[${flowId}] Cart validation failed`);
}
logger.debug(`[${flowId}] Cart validated`);
// Step 2: Process payment
await processPayment(cartId);
const payment = useStore.getState().payment;
if (!payment.authorized) {
throw new Error(`[${flowId}] Payment authorization failed`);
}
logger.debug(`[${flowId}] Payment processed`);
// Step 3: Confirm order
await confirmOrder(cartId);
logger.info(`[${flowId}] Checkout flow completed`);
}
```
---
## Pattern: Flow Object
**Problem:** Long async functions with many steps become unwieldy.
```typescript
interface FlowStep<TContext> {
name: string;
execute: (context: TContext) => Promise<void>;
validate?: (context: TContext) => void; // Postcondition check
}
interface CheckoutContext {
cartId: string;
flowId: string;
}
const checkoutSteps: FlowStep<CheckoutContext>[] = [
{
name: 'validateCart',
execute: async (ctx) => {
await validateCart(ctx.cartId);
},
validate: (ctx) => {
const cart = useStore.getState().cart;
if (!cart.validated) {
throw new Error(`[${ctx.flowId}] Cart not validated`);
}
},
},
{
name: 'processPayment',
execute: async (ctx) => {
await processPayment(ctx.cartId);
},
validate: (ctx) => {
const payment = useStore.getState().payment;
if (!payment.authorized) {
throw new Error(`[${ctx.flowId}] Payment not authorized`);
}
},
},
{
name: 'confirmOrder',
execute: async (ctx) => {
await confirmOrder(ctx.cartId);
},
},
];
async function executeFlow<TContext>(
steps: FlowStep<TContext>[],
context: TContext,
flowName: string
) {
const flowId = `${flowName}-${Date.now()}`;
logger.info(`[${flowId}] Starting flow`, context);
for (const step of steps) {
logger.debug(`[${flowId}] Executing: ${step.name}`);
try {
await step.execute(context);
if (step.validate) {
step.validate(context);
}
logger.debug(`[${flowId}] Completed: ${step.name}`);
} catch (error) {
logger.error(`[${flowId}] Failed at: ${step.name}`, { error: error.message });
throw error;
}
}
logger.info(`[${flowId}] Flow completed`);
}
// Usage
await executeFlow(checkoutSteps, { cartId, flowId }, 'checkout');
```
---
## Pattern: Flow State Tracking
**Problem:** Components need to know current flow state for UI feedback.
```typescript
type CheckoutFlowState =
| { status: 'idle' }
| { status: 'loading'; step: string }
| { status: 'ready' }
| { status: 'processing'; step: string }
| { status: 'complete'; orderId: string }
| { status: 'error'; message: string; step: string };
const useCheckoutStore = create<{
flowState: CheckoutFlowState;
setFlowState: (state: CheckoutFlowState) => void;
}>((set) => ({
flowState: { status: 'idle' },
setFlowState: (flowState) => set({ flowState }),
}));
async function checkout(cartId: string) {
const { setFlowState } = useCheckoutStore.getState();
try {
setFlowState({ status: 'processing', step: 'validating' });
await validateCart(cartId);
setFlowState({ status: 'processing', step: 'payment' });
await processPayment(cartId);
setFlowState({ status: 'processing', step: 'confirming' });
const order = await confirmOrder(cartId);
setFlowState({ status: 'complete', orderId: order.id });
} catch (error) {
setFlowState({
status: 'error',
message: error.message,
step: useCheckoutStore.getState().flowState.step,
});
}
}
// Component usage
function CheckoutScreen() {
const flowState = useCheckoutStore((s) => s.flowState);
if (flowState.status === 'processing') {
return <Loading step={flowState.step} />;
}
if (flowState.status === 'error') {
return <Error message={flowState.message} step={flowState.step} />;
}
if (flowState.status === 'complete') {
return <Confirmation orderId={flowState.orderId} />;
}
// ... render based on state
}
```
---
## Pattern: Integration Testing Flows
**Problem:** Unit tests for individual functions don't catch flow-level bugs.
```typescript
describe('Checkout Flow', () => {
beforeEach(() => {
useCheckoutStore.getState()._reset();
});
it('completes full checkout flow', async () => {
const cartId = 'test-cart';
const store = useCheckoutStore;
// Setup: Add items to cart
store.getState().addItem({ id: 'item-1', price: 100 });
// Execute full flow
await store.getState().checkout(cartId);
// Verify final state
expect(store.getState().flowState.status).toBe('complete');
expect(store.getState().flowState.orderId).toBeDefined();
});
it('handles payment failure gracefully', async () => {
// Mock payment to fail
mockPaymentApi.mockRejectedValueOnce(new Error('Card declined'));
await expect(
store.getState().checkout(cartId)
).rejects.toThrow('Card declined');
expect(store.getState().flowState.status).toBe('error');
expect(store.getState().flowState.step).toBe('payment');
});
});
```
---
## Pattern: Flow Documentation
Document complex flows with diagrams for team understanding:
```markdown
## Checkout Flow
### Happy Path
```
┌─────────┐ ┌──────────────┐ ┌─────────────────┐ ┌─────────────┐
│ Start │────▶│ Validate Cart│────▶│ Process Payment │────▶│ Confirm │
└─────────┘ └──────────────┘ └─────────────────┘ └─────────────┘
│ │ │
▼ ▼ ▼
Postcondition: Postcondition: Postcondition:
cart.validated payment.authorized order.created
│
▼
┌──────────┐
│ Complete │
└──────────┘
```
### Error States
Any step can fail → transition to ERROR state with step context.
From ERROR: user can retry or exit.
```
---
## Checklist: Designing Complex Flows
Before implementing:
- [ ] Sketch state diagram (even on paper)
- [ ] Identify all states, including error states
- [ ] Document preconditions for each transition
- [ ] Document postconditions to verify
- [ ] Plan how to surface state to UI
During implementation:
- [ ] Verify preconditions before each step
- [ ] Validate postconditions after each step
- [ ] Log state transitions with flow ID
- [ ] Handle errors at each step with context
- [ ] Surface flow state for UI feedback
After implementation:
- [ ] Integration test for happy path
- [ ] Integration test for error at each step
- [ ] Verify logs are sufficient for debugging
- [ ] Document flow for team
---
## When to Use XState
Consider XState when:
- Flow has > 6 states
- Complex branching/parallel states
- Need visualization/debugging tools
- State machine is shared across team
For simpler flows, explicit steps with validation (as shown above) are often sufficient and more readable.Related Skills
terraform-state-manager
Terraform State Manager - Auto-activating skill for DevOps Advanced. Triggers on: terraform state manager, terraform state manager Part of the DevOps Advanced skill category.
react-hook-creator
React Hook Creator - Auto-activating skill for Frontend Development. Triggers on: react hook creator, react hook creator Part of the Frontend Development skill category.
react-context-setup
React Context Setup - Auto-activating skill for Frontend Development. Triggers on: react context setup, react context setup Part of the Frontend Development skill category.
react-component-generator
React Component Generator - Auto-activating skill for Frontend Development. Triggers on: react component generator, react component generator Part of the Frontend Development skill category.
mermaid-state-diagram-creator
Mermaid State Diagram Creator - Auto-activating skill for Visual Content. Triggers on: mermaid state diagram creator, mermaid state diagram creator Part of the Visual Content skill category.
building-gitops-workflows
This skill enables Claude to construct GitOps workflows using ArgoCD and Flux. It is designed to generate production-ready configurations, implement best practices, and ensure a security-first approach for Kubernetes deployments. Use this skill when the user explicitly requests "GitOps workflow", "ArgoCD", "Flux", or asks for help with setting up a continuous delivery pipeline using GitOps principles. The skill will generate the necessary configuration files and setup code based on the user's specific requirements and infrastructure.
cursor-composer-workflows
Master Cursor Composer for multi-file AI editing, scaffolding, and refactoring. Triggers on "cursor composer", "multi-file edit", "cursor generate files", "composer workflow", "cursor scaffold", "Cmd+I".
flowstudio-power-automate-mcp
Connect to and operate Power Automate cloud flows via a FlowStudio MCP server. Use when asked to: list flows, read a flow definition, check run history, inspect action outputs, resubmit a run, cancel a running flow, view connections, get a trigger URL, validate a definition, monitor flow health, or any task that requires talking to the Power Automate API through an MCP tool. Also use for Power Platform environment discovery and connection management. Requires a FlowStudio MCP subscription or compatible server — see https://mcp.flowstudio.app
flowstudio-power-automate-debug
Debug failing Power Automate cloud flows using the FlowStudio MCP server. Load this skill when asked to: debug a flow, investigate a failed run, why is this flow failing, inspect action outputs, find the root cause of a flow error, fix a broken Power Automate flow, diagnose a timeout, trace a DynamicOperationRequestFailure, check connector auth errors, read error details from a run, or troubleshoot expression failures. Requires a FlowStudio MCP subscription — see https://mcp.flowstudio.app
flowstudio-power-automate-build
Build, scaffold, and deploy Power Automate cloud flows using the FlowStudio MCP server. Load this skill when asked to: create a flow, build a new flow, deploy a flow definition, scaffold a Power Automate workflow, construct a flow JSON, update an existing flow's actions, patch a flow definition, add actions to a flow, wire up connections, or generate a workflow definition from scratch. Requires a FlowStudio MCP subscription — see https://mcp.flowstudio.app
upgrading-react-native
Upgrades React Native apps to newer versions by applying rn-diff-purge template diffs, updating package.json dependencies, migrating native iOS and Android configuration, resolving CocoaPods and Gradle changes, and handling breaking API updates. Use when upgrading React Native, bumping RN version, updating from RN 0.x to 0.y, or migrating Expo SDK alongside a React Native upgrade.
react-native-brownfield-migration
Provides an incremental adoption strategy to migrate native iOS or Android apps to React Native or Expo using @callstack/react-native-brownfield for initial setup. Use when planning migration steps, packaging XCFramework/AAR artifacts, and integrating them into host apps.