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.

242 stars

Best use case

react-state-flows is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. 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.

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.

Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.

Practical example

Example input

Use the "react-state-flows" skill to help with this workflow task. Context: 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.

Example output

A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.

When to use this skill

  • Use this skill when you want a reusable workflow rather than writing the same prompt again and again.

When not to use this skill

  • Do not use this when you only need a one-off answer and do not need a reusable workflow.
  • Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/react-state-flows/SKILL.md --create-dirs "https://raw.githubusercontent.com/aiskillstore/marketplace/main/skills/cjharmath/react-state-flows/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/react-state-flows/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How react-state-flows Compares

Feature / Agentreact-state-flowsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/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.

Related Guides

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

react-native-design

242
from aiskillstore/marketplace

Master React Native styling, navigation, and Reanimated animations for cross-platform mobile development. Use when building React Native apps, implementing navigation patterns, or creating performant animations.

react-useeffect

242
from aiskillstore/marketplace

React useEffect best practices from official docs. Use when writing/reviewing useEffect, useState for derived values, data fetching, or state synchronization. Teaches when NOT to use Effect and better alternatives.

react-dev

242
from aiskillstore/marketplace

This skill should be used when building React components with TypeScript, typing hooks, handling events, or when React TypeScript, React 19, Server Components are mentioned. Covers type-safe patterns for React 18-19 including generic components, proper event typing, and routing integration (TanStack Router, React Router).

tdd-workflows-tdd-refactor

242
from aiskillstore/marketplace

Use when working with tdd workflows tdd refactor

tdd-workflows-tdd-red

242
from aiskillstore/marketplace

Generate failing tests for the TDD red phase to define expected behavior and edge cases.

tdd-workflows-tdd-green

242
from aiskillstore/marketplace

Implement the minimal code needed to make failing tests pass in the TDD green phase.

tdd-workflows-tdd-cycle

242
from aiskillstore/marketplace

Use when working with tdd workflows tdd cycle

react-state-management

242
from aiskillstore/marketplace

Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query. Use when setting up global state, managing server state, or choosing between state management solutions.

react-native-architecture

242
from aiskillstore/marketplace

Build production React Native apps with Expo, navigation, native modules, offline sync, and cross-platform patterns. Use when developing mobile apps, implementing native integrations, or architecting React Native projects.

react-modernization

242
from aiskillstore/marketplace

Upgrade React applications to latest versions, migrate from class components to hooks, and adopt concurrent features. Use when modernizing React codebases, migrating to React Hooks, or upgrading to latest React versions.

react-flow-node-ts

242
from aiskillstore/marketplace

Create React Flow node components with TypeScript types, handles, and Zustand integration. Use when building custom nodes for React Flow canvas, creating visual workflow editors, or implementing node-based UI components.

react-flow-architect

242
from aiskillstore/marketplace

Expert ReactFlow architect for building interactive graph applications with hierarchical node-edge systems, performance optimization, and auto-layout integration. Use when Claude needs to create or optimize ReactFlow applications for: (1) Interactive process graphs with expand/collapse navigation, (2) Hierarchical tree structures with drag & drop, (3) Performance-optimized large datasets with incremental rendering, (4) Auto-layout integration with Dagre, (5) Complex state management for nodes and edges, or any advanced ReactFlow visualization requirements.