React stability

From Vrooli/Vrooli · View interactive version

React stability is an AI agent skill from the GitHub repository Vrooli/Vrooli. Prioritize **hardening React UI components against runtime crashes** across this scenario.

How to use this skill

Skill file

Steer focus: React Stability

Prioritize hardening React UI components against runtime crashes across this scenario.

Your goal is to ensure the UI degrades gracefully under unexpected data, user actions, and edge cases, rather than crashing with a white screen or cryptic error.

Do not break functionality, regress tests, or introduce new features. All changes must maintain or improve overall completeness and reliability.

Required reading:


**0. Tooling Prerequisites (Run First)**

Before manual code review, verify that automated tooling is configured to catch React-specific bugs. Proper TypeScript and ESLint configuration catches 80%+ of runtime crashes automatically.

Step 1: Run automated type-safety checks
scenario-auditor scan {{TARGET}} --rules TS_CONFIG_STRICT,ESLINT_SAFETY_RULES,TS_DANGEROUS_PATTERNS
Step 2: Auto-fix what can be fixed
scenario-auditor fix {{TARGET}} --rules TS_CONFIG_STRICT --dry-run
scenario-auditor fix {{TARGET}} --rules TS_CONFIG_STRICT

For ESLint and pattern issues: follow remediation guidance in scan output.

Step 3: Run linting and fix errors
cd scenarios/{{TARGET}}/ui && pnpm lint

Priority order for fixes:

  1. rules-of-hooks errors - guaranteed crash bugs, fix ALL before proceeding
  2. no-non-null-assertion errors - using ! hides null bugs that crash at runtime
  3. no-unsafe-* warnings - operations on any types that may crash
  4. exhaustive-deps warnings - potential stale closure bugs

**0.5 Protected Rules - NEVER REMOVE**

The following rules exist because UI crashes are the #1 production issue. They catch bugs at compile/lint time that would otherwise crash at runtime.

⚠️ THESE RULES MUST NEVER BE REMOVED, DISABLED, OR WEAKENED:

| Rule | Location | What it prevents |

|------|----------|------------------|

| strict: true | tsconfig.json | Entire class of null/undefined bugs |

| noUncheckedIndexedAccess: true | tsconfig.json | arr[0].method() crashes when array is empty |

| react-hooks/rules-of-hooks | eslint.config.js | React Error #310 (early returns before hooks) |

| @typescript-eslint/no-non-null-assertion | eslint.config.js | ! operator that hides null bugs |

| @typescript-eslint/no-explicit-any | eslint.config.js | any type that disables all checking |

| import/no-cycle | eslint.config.js | Circular dependencies causing "Cannot access X before initialization" |

When you encounter errors from these rules:

✅ DO:

❌ DON'T:

If fixing errors causes significant churn: Fix them incrementally. A scenario with these rules and some unfixed errors is safer than one without the rules at all - the errors serve as documentation of known risks


**1. Layered Architecture (Strongly Recommended)**

Structure React applications with clear layers to create natural testing seams and ensure validation happens at the right boundary:

Components (Pure rendering - receives validated data, no logic)
    ↓
Hooks (React state management - calls controllers, handles UI state)
    ↓
Controllers (Page-specific orchestration - coordinates services)
    ↓
Services (Pure functions & API calls - handles validation, returns typed data)

Why this pattern:

Layer responsibilities:

| Layer | Responsibility | Tests |

|-------|---------------|-------|

| Components | Pure rendering, props → JSX | Snapshot/visual tests |

| Hooks | UI state, context, call controllers | Hook unit tests |

| Controllers | Orchestrate services, page-level logic | Integration tests |

| Services | API calls, data transform, runtime validation | Unit tests, contract tests |

Key principle: Components should never see invalid data. Validation failures are caught in the Service layer and surfaced as typed error states that the UI can handle gracefully.

This pattern is strongly recommended for all React scenarios in Vrooli. The exact directory structure may vary (e.g., src/services/, src/hooks/, etc.), but the layer separation should be maintained.


**2. Error Boundaries: Strategic Placement**

Anti-patterns to fix:


**3. Defensive Data Access**

Audit components for unsafe assumptions about data shape:

```tsx

{(data?.items ?? []).map((item) => (

// render item

))}

```

Priority areas:


**4. Hook Discipline (Critical)**

React hooks have strict rules that, when violated, cause runtime crashes. This section covers bugs that ESLint catches automatically (Section 0) plus manual detection for edge cases.

**4.1 Rules of Hooks Violations (React Error #310)**

React Error #310 ("Rendered fewer hooks than expected") occurs when the number of hooks changes between renders. This is a guaranteed crash - no error boundary can catch it.

Root cause: React tracks hooks by call order. If render N calls 8 hooks but render N+1 calls 9 hooks, React crashes.

The #1 cause: Early returns placed BEFORE hooks

This pattern looks innocent but is a crash waiting to happen:

// ❌ WRONG - hooks after early return won't always execute
function MessageList({ messages }) {
  const [filter, setFilter] = useState("");           // Hook 1
  const theme = useContext(ThemeContext);             // Hook 2

  // Early return BEFORE all hooks are called!
  if (messages.length === 0) {
    return <EmptyState />;  // Returns here when empty
  }

  // Hook 3 - ONLY executes when messages.length > 0
  const filtered = useMemo(() =>
    messages.filter(m => m.includes(filter)),
    [messages, filter]
  );

  return <List items={filtered} />;
}
// When messages changes from [] to [msg], hook count changes 2→3 = CRASH
// ✅ CORRECT - all hooks execute every render, early return AFTER
function MessageList({ messages }) {
  const [filter, setFilter] = useState("");           // Hook 1
  const theme = useContext(ThemeContext);             // Hook 2

  // Hook 3 - ALWAYS executes, handles empty case internally
  const filtered = useMemo(() => {
    if (messages.length === 0) return [];
    return messages.filter(m => m.includes(filter));
  }, [messages, filter]);

  // Early return AFTER all hooks
  if (messages.length === 0) {
    return <EmptyState />;
  }

  return <List items={filtered} />;
}

Other causes:

Manual detection methodology (when ESLint isn't catching it):

  1. Count all hooks in each component (useState, useEffect, useMemo, useCallback, useContext, useRef, useReducer, custom use* hooks)
  2. Identify ALL early returns - any return statement before the component's final return
  3. Verify NO hooks appear after ANY early return
  4. If hooks appear after early returns → MOVE the early return after all hooks
**4.2 useMemo / useCallback Hygiene**

```tsx

// ❌ WRONG - new array on every render when items is empty

const filtered = useMemo(() => items?.filter(x => x.active) ?? [], [items]);

// ✅ CORRECT - stable reference for empty case

const EMPTY_ITEMS: Item[] = []; // Outside component

const filtered = useMemo(() => {

if (!items || items.length === 0) return EMPTY_ITEMS;

return items.filter(x => x.active);

}, [items]);

```

**4.3 useEffect Correctness**
**4.4 Dependency Stability**
**4.5 State Updates During Render**

**5. TypeScript Strictness**

Verify TypeScript configuration provides adequate safety:

Do not force noUncheckedIndexedAccess if it causes excessive churn; document it as a future recommendation instead.


**6. Component State Management**

Ensure components explicitly handle all states of async data:


**7. Runtime Validation with Protobuf + Zod (Recommended)**

TypeScript types are erased at runtime - they cannot catch API shape mismatches, null values in unexpected places, or data corruption. For production reliability, use runtime validation at system boundaries.

**7.1 The Type Safety Chain**
Proto Definitions (packages/proto/schemas/)
    ↓ code generation
Generated TS Types (@vrooli/proto-types)
    ↓ derive validation schemas
Zod Schemas (ui/src/shared/api/schemas/)
    ↓ runtime validation in services
Validated Data → Components

Why this chain:

**7.2 When to Validate**

| Boundary | Validate? | Why |

|----------|-----------|-----|

| API responses | YES | External data, contract may drift |

| WebSocket messages | YES | External data, parsing may fail |

| User input | YES | Never trust user input |

| Internal service calls | No | Already validated at entry |

| Component props | No | Data validated before reaching components |

Key principle: Validate once at the system boundary (in Services), then trust the data as it flows through the application.

**7.3 Validation Pattern**

Services should return a discriminated union that makes validation failures explicit:

// In your service layer
import { z } from 'zod';

const PlanSchema = z.object({
  plan_name: z.string(),
  plan_tier: z.string(),
  billing_interval: z.enum(['month', 'year', 'one_time']),
  // ... derived from proto types
});

type ParseResult<T> =
  | { success: true; data: T }
  | { success: false; error: string };

export function fetchPlan(id: string): Promise<ParseResult<Plan>> {
  // Fetch, validate, return typed result or error
}

This pattern:

**7.4 Proto Integration**

When creating or modifying API contracts:

  1. Define the schema in packages/proto/schemas/ (see packages/proto/README.md for guidance)
  2. Run cd packages/proto && make generate to regenerate types
  3. Create corresponding Zod schemas that mirror the proto structure
  4. Use the generated TS types for compile-time safety, Zod for runtime validation

Note: Zod schemas should mirror proto types closely. If the proto has optional string field, the Zod schema should use z.string().optional(). This keeps the validation contract aligned with the API contract.


**8. Memory Management with Visited Tracker**

Use the visited-tracker-tools skill for tracking visited files, with LOCATION set to scenarios/{{TARGET}}/ui and TAG set to react-stability.


**9. Output Expectations**

You may update:

You must:

Focus this loop on practical, targeted stability improvements that prevent white-screen crashes and make the UI resilient to real-world data variability.

Avoid superficial changes that rename variables or restructure code without materially improving crash resistance.


**11. Documentation**

Use knowledge-observatory-tools to read the current problems doc for {{TARGET}}, then update the Stability Issues section with your findings (crash-prone patterns, error boundary gaps, TypeScript/ESLint improvements, remaining stability risks).

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.