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.
What this skill does
# 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
│
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.