Alexis Le Dain 04c68e483a
Add React language track with agents, skills, rules, and commands (#2024)
* feat(rules): add rules/react/ track

Five rule files mirroring per-language convention (coding-style,
hooks, patterns, security, testing). Each has `paths:` glob
frontmatter for auto-activation when editing matching files.

- coding-style.md: file extensions, naming, JSX, RSC boundary
- hooks.md: React hooks (NOT Claude Code hooks) — rules-of-hooks,
  dep arrays, cleanup, memoization, React 19 additions
- patterns.md: container/presentational split, state location
  decision tree, Suspense + error boundaries, forms, data fetching
- security.md: dangerouslySetInnerHTML, unsafe URL schemes,
  server-action validation, env-var leaks, CSP
- testing.md: RTL queries, userEvent, async, MSW, axe, anti-patterns

Each file extends typescript/* and common/* rules.

* feat(skills): add react-patterns, react-testing, react-performance

Three new skills under skills/ following the SKILL.md convention.

- react-patterns: React 18/19 idioms — hooks discipline, state
  location decision tree, server/client component boundary,
  Suspense + error boundaries, form actions (React 19), data
  fetching matrix, composition recipes, accessibility-first.
- react-testing: React Testing Library + Vitest/Jest, query
  priority order, userEvent, MSW network mocking, axe a11y
  assertions, RTL vs Playwright CT boundary, TDD workflow.
- react-performance: 70-rule performance ruleset adapted from
  Vercel Labs react-best-practices (MIT) across 8 priority
  categories — waterfalls, bundle size, server-side, client
  fetch, re-render, rendering, JS micro, advanced patterns.
  Includes Lighthouse / Web Vitals mapping and attribution to
  upstream.

Cross-links between the three skills and out to frontend-patterns,
accessibility, e2e-testing, tdd-workflow.

* feat(agents): add react-reviewer and react-build-resolver

Two new agents covering React-specific code review and build error
resolution, plus matching .kiro/ mirrors and a routing pointer
edit on typescript-reviewer.

- react-reviewer: slim React-only lanes (hooks rules,
  dangerouslySetInnerHTML, unsafe URL schemes, key prop, state
  mutation, derived-state-in-effect, server/client component
  boundary, accessibility, render performance, Server Action
  validation, env-var leaks). Explicitly delegates generic
  TypeScript/async/Node concerns to typescript-reviewer. Both
  agents should be invoked together on .tsx/.jsx PRs.
- react-build-resolver: React build/bundler/runtime hydration
  failures across Vite, webpack, Next.js, CRA, Parcel, esbuild,
  Bun, Rsbuild. Handles JSX/TSX compile errors, tsconfig fixes,
  Next.js App Router server/client boundary errors, hydration
  mismatches, duplicated React copies, Tailwind/PostCSS pipeline.
- .kiro/agents/react-reviewer.json + react-build-resolver.json:
  Kiro IDE format mirrors following the per-language precedent.
- typescript-reviewer: routing pointer added to its MEDIUM React
  block — defers to /react-review for React-specific concerns
  while keeping its block as fallback for repos that only invoke
  typescript-reviewer.

All agents carry the standard Prompt Defense Baseline stanza.

* feat(commands): add /react-review /react-build /react-test

Three new slash commands invoking the React agents.

- /react-review: invokes react-reviewer. Documents the routing
  rule with typescript-reviewer — both should run together on
  TSX/JSX PRs. Lists CRITICAL/HIGH/MEDIUM rule categories and
  the automated checks (eslint with react-hooks + jsx-a11y,
  tsc --noEmit, npm audit).
- /react-build: invokes react-build-resolver. Documents bundler
  detection, common failure patterns, fix strategy, and stop
  conditions.
- /react-test: enforces TDD with React Testing Library + Vitest
  or Jest, behavior-focused queries, userEvent + MSW patterns,
  axe accessibility assertions, coverage targets.

Each command file has the required description: frontmatter and
follows the per-language command convention (cpp-test, go-test,
kotlin-test, etc.).

* chore: wire react track into manifests and stack mappings

- agent.yaml: add react-patterns, react-performance, react-testing
  to the skills array; add react-build, react-review, react-test to
  the commands array (alphabetically inserted to satisfy the
  ci/agent-yaml-surface sync test).
- config/project-stack-mappings.json: extend the `react` stack
  entry — add "react" to rules array (was ["common","typescript",
  "web"]); add react-patterns, react-performance, react-testing,
  accessibility to the skills array.
- docs/COMMAND-REGISTRY.json: bump totalCommands 75 -> 78; add
  three new entries (react-build, react-review, react-test) with
  primaryAgents / allAgents / skills wiring. react-review's
  allAgents includes typescript-reviewer to reflect the dual-agent
  routing convention.
- CLAUDE.md: add Skills-table row mapping *.tsx / *.jsx /
  components/** to react-patterns + react-testing skills and
  the /react-review, /react-build, /react-test commands.

* chore(catalog): sync counts to 62 agents / 78 commands / 235 skills

Auto-generated via `node scripts/ci/catalog.js --write --text`
after the react track additions:

- 2 new agents: react-reviewer, react-build-resolver (60 -> 62)
- 3 new commands: react-build, react-review, react-test (75 -> 78)
- 3 new skills: react-patterns, react-performance, react-testing
  (232 -> 235)

Files updated by the catalog sync:
- .claude-plugin/plugin.json description string
- .claude-plugin/marketplace.json plugin description
- README.md quick-start summary, project tree, feature parity tables
- README.zh-CN.md quick-start summary
- AGENTS.md project structure summary
- docs/zh-CN/README.md parity table
- docs/zh-CN/AGENTS.md project structure summary

All counts now match the filesystem catalog (verified by
ci/catalog.test.js).

* feat(kiro): add react agent markdown companions to JSON entries

* feat(kiro): add react skills into manifests

* fix(ci): sync catalog counts, registry, and package files for react track

- .claude-plugin/{plugin,marketplace}.json: bump description counts to 62/235/78
- docs/COMMAND-REGISTRY.json: regenerate to include quality-gate and react commands
- package.json: add skills/react-{patterns,performance,testing}/ to files allowlist so npm-publish-surface aligns with install-modules manifest

* fix(react): address PR #2024 review feedback

Critical:
- Remove undefined/.claude/session-aliases.json containing __proto__ prototype-pollution
  fixture committed by accident in a7333c14

High:
- agents/react-build-resolver.md: replace brittle `test -o $(grep -l ...)` and
  `test -a -n $(grep ...)` detection with explicit `{ ... || grep -q ...; }` so
  bundler detection no longer breaks when grep returns empty
- agents/react-build-resolver.md: drop hardcoded `npm i react@^19 react-dom@^19`
  remediation; replace with version-agnostic pair-upgrade note that honors the
  project's installed major (17/18/19) — surgical fix principle
- commands/react-review.md: guard `tsc --noEmit -p tsconfig.json` with
  `[ -f tsconfig.json ] &&` so the review skips cleanly on JS-only projects

Medium:
- rules/react/security.md: correct the React-18-blocks-javascript-URL claim
  (React only warns in dev; production navigation is not blocked)
- rules/react/security.md: correct CRA env-var exposure row (CRA exposes
  REACT_APP_*, NODE_ENV, PUBLIC_URL — not 'all' variables)
- skills/react-testing/SKILL.md: instantiate QueryClient once outside the
  wrapper closure so React Query cache survives re-renders (flaky-test fix)
- skills/react-testing/SKILL.md: restore console.error spy with mockRestore()
  in a try/finally so the mock does not leak across tests
- commands/react-test.md: switch outer example-session fence to 4 backticks
  so the inner ```tsx/```bash blocks don't prematurely terminate it

* fix(kiro): mirror react-build-resolver react 19 conditional remediation

Discussion r3272907106 flagged the kiro json variant still carrying the hardcoded
'npm i react@^19 react-dom@^19' line that the .md companion already dropped.
Replace with the same conditional, version-agnostic guidance so both variants
stay in sync.

* fix(react): bump react-build example session fence to 4 backticks

Discussion r3272907144 flagged the same nested-fence issue in
commands/react-build.md that we fixed earlier in commands/react-test.md.
The outer triple-backtick text block was being prematurely terminated by
the inner bash/tsx fences inside the Example Session.

* fix(react): bump react-review example usage fence to 4 backticks

Discussion r3272907201 flagged the same nested-fence issue in
commands/react-review.md. The outer triple-backtick text block was
being prematurely terminated by the inner tsx/ts fences inside the
Example Usage transcript.

* fix(docs): clarify commands row as legacy shims in feature parity table

Discussion r3272912003: README comparison table said 'PASS: 78 commands'
while the install-section and quick-start prose use 'legacy command shims'.
Aligned the comparison-table cell to 'PASS: 78 commands (legacy shims)' so
the count word survives the catalog-validator regex while making the legacy
nature explicit.

Widened the catalog comparison-table commands regex to tolerate an optional
parenthetical after the count word, so both the existing 'X commands' and
the new 'X commands (legacy shims)' phrasings validate without breaking
older READMEs/translations.

* Update rules/react/security.md

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix(react): guard tsc in react-build-resolver diagnostic commands

Discussion r3288910205: the agent prompt instructed an unconditional
'tsc --noEmit -p tsconfig.json', which adds noise (or hard-fails) on
JavaScript-only projects with no tsconfig.json or no installed TypeScript.

Replaced with 'test -f tsconfig.json && npx --yes tsc --noEmit -p tsconfig.json'
in both variants:
- agents/react-build-resolver.md
- .kiro/agents/react-build-resolver.json (prompt string mirrored)

Mirrors the same guard already applied to commands/react-review.md in de135f61.

* fix(react): pin tsc resolution to local install in build resolver

Discussion r3289054157: previous fix used 'npx --yes tsc' which auto-installs
the latest TypeScript from npm when none is local, producing version drift
and non-reproducible typecheck results across machines.

Switched to 'npx --no-install tsc' in both variants so the diagnostic uses
only the project's pinned TypeScript and fails fast if it isn't installed:
- agents/react-build-resolver.md
- .kiro/agents/react-build-resolver.json (prompt string mirrored)

* feat(counts): resolve counts for agents, skills...

* fix(ci): regen command registry for golang-testing entry

Removes stale kotlin-patterns entry to satisfy command-registry:check.

* fix: keep local Claude settings out of React track PR

---------

Co-authored-by: AlexisLeDain <a.ledain@docoon.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Affaan Mustafa <affaan@dcube.ai>
2026-05-28 07:32:52 -04:00

11 KiB

name, description, origin
name description origin
react-patterns React 18/19 patterns including hooks discipline, server/client component boundaries, Suspense + error boundaries, form actions, data fetching, state management decision trees, and accessibility-first composition. Use when writing or reviewing React components. ECC

React Patterns

Idiomatic React 18/19 patterns for building robust, accessible, performant component trees.

When to Activate

  • Writing or modifying React function components, custom hooks, or component trees
  • Reviewing JSX/TSX files
  • Designing state shape or component composition
  • Migrating class components or older forwardRef/useEffect-heavy code
  • Choosing between local state, lifted state, context, and external stores
  • Working with Server Components / Client Components (Next.js App Router, RSC)
  • Implementing forms with React 19 actions or controlled inputs
  • Wiring data fetching with TanStack Query / SWR / RSC

Core Principles

1. Render is a Pure Function of Props and State

// Good: derive during render
function Cart({ items }: { items: CartItem[] }) {
  const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  return <span>{formatMoney(total)}</span>;
}

// Bad: derived state stored separately
function Cart({ items }: { items: CartItem[] }) {
  const [total, setTotal] = useState(0);
  useEffect(() => {
    setTotal(items.reduce((sum, i) => sum + i.price * i.qty, 0));
  }, [items]);
  return <span>{formatMoney(total)}</span>;
}

Derived state in useEffect adds a render cycle, can desync, and obscures the data flow.

2. Side Effects Outside Render

Effects, mutations, network calls, and subscriptions live in event handlers or useEffect — never in the render body.

3. Composition Over Inheritance

React has no inheritance model for components. Compose with children, render props, or component props.

Hooks Discipline

See rules/react/hooks.md for the full ruleset. Highlights:

  • Top-level only, never conditional
  • Cleanup every subscription, interval, listener
  • Functional updater (setX(prev => prev + 1)) when new state depends on old
  • Default position: do not memoize — add useMemo/useCallback only when a profiler or a dependency chain proves it matters
  • Extract a custom hook only when the same hook sequence appears in 2+ components

State Location Decision Tree

Used by one component?
  -> useState inside it

Used by parent + a few descendants?
  -> lift to nearest common ancestor

Used across distant branches AND low-frequency reads (theme, auth, locale)?
  -> React Context

High-frequency updates shared across the tree?
  -> external store (Zustand, Jotai, Redux Toolkit)

Derived from a server?
  -> server-state library (TanStack Query, SWR, RSC fetch)

Most pages do not need context or a global store. Resist abstraction until duplicated lifting becomes painful.

Server / Client Components (RSC)

// Server Component - default, async, never ships JS for itself
export default async function ProductPage({ params }: { params: { id: string } }) {
  const product = await db.product.findUnique({ where: { id: params.id } });
  if (!product) notFound();
  return <ProductView product={product} />;
}

// Client Component - opt in with "use client"
"use client";
export function AddToCartButton({ productId }: { productId: string }) {
  const [pending, startTransition] = useTransition();
  return (
    <button
      disabled={pending}
      onClick={() => startTransition(() => addToCart(productId))}
    >
      {pending ? "Adding..." : "Add to cart"}
    </button>
  );
}

Boundaries:

  • Server -> Client: pass serializable props or children
  • Client -> Server: invoke Server Actions via <form action={...}> or imperatively from event handlers
  • Never import a Server Component from a Client Component file — compose them via children instead

Suspense + Error Boundaries

<ErrorBoundary fallback={<ErrorView />}>
  <Suspense fallback={<UserSkeleton />}>
    <UserDetail id={id} />
  </Suspense>
</ErrorBoundary>
  • Place Suspense boundaries close to the data, not at the route root — progressively reveal content
  • Error Boundary remains a class API; use react-error-boundary for a hook-friendly wrapper
  • A boundary catches errors thrown during render, lifecycle, and constructors of its children — NOT in event handlers or async code

Forms

React 19 form actions (preferred for new code)

"use client";
import { useActionState } from "react";

const initial = { error: null as string | null };

async function updateUserAction(_prev: typeof initial, formData: FormData) {
  "use server";
  const parsed = UserSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { error: "Invalid input" };
  await db.user.update({ where: { id: parsed.data.id }, data: parsed.data });
  return { error: null };
}

export function UserForm() {
  const [state, formAction, pending] = useActionState(updateUserAction, initial);
  return (
    <form action={formAction}>
      <input name="name" required />
      <button type="submit" disabled={pending}>Save</button>
      {state.error && <p role="alert">{state.error}</p>}
    </form>
  );
}

Controlled inputs

Use controlled when the value drives other UI, formats on every keystroke, or implements real-time validation.

Complex forms

For multi-step forms, dynamic field arrays, or cross-field validation: use a library (React Hook Form, TanStack Form). Roll-your-own state management for forms past trivial complexity is a maintenance trap.

Data Fetching Decision Matrix

Need Tool
Per-request data in Next.js App Router RSC await fetch()
Client-side cache + mutations + invalidation TanStack Query
Lightweight client cache + revalidation SWR
Real-time subscriptions Server-Sent Events, WebSockets, or the lib's subscription API
One-off fire-and-forget fetch() in an event handler

Avoid useEffect + fetch for application data — race conditions, no cache, no retry, no Suspense integration.

Composition Recipes

Slot via children

<Layout>
  <Header />
  <Main>{content}</Main>
</Layout>

Named slots

<Page header={<Nav />} sidebar={<Filters />}>
  <Results />
</Page>

Compound components (shared state via Context)

<Tabs defaultValue="profile">
  <Tabs.List>
    <Tabs.Trigger value="profile">Profile</Tabs.Trigger>
    <Tabs.Trigger value="settings">Settings</Tabs.Trigger>
  </Tabs.List>
  <Tabs.Panel value="profile"><Profile /></Tabs.Panel>
  <Tabs.Panel value="settings"><Settings /></Tabs.Panel>
</Tabs>

Render prop / function-as-child

Useful when the parent needs to pass parameters to the rendered output:

<DataLoader id={id}>
  {({ data, isLoading }) => isLoading ? <Spinner /> : <UserCard user={data} />}
</DataLoader>

Modern alternative: a hook (useData(id)) returning the same shape — usually cleaner.

Performance

When React.memo Actually Helps

Wrap a component in React.memo only when:

  1. It re-renders frequently
  2. Its props are usually the same between renders
  3. Its render is measurably expensive

React.memo adds an equality check on every render. If props differ on most renders, the check is pure overhead.

Avoiding Render Cascades

  • Lift state down rather than up where possible
  • Split context: one context per concern, so a change to themeContext does not re-render auth consumers
  • Use useSyncExternalStore for external state libraries — required for safe concurrent rendering

Lists

  • Provide stable key props (database id, not array index)
  • Virtualize long lists with @tanstack/react-virtual or react-window once visible item count exceeds ~50 with non-trivial rows

Accessibility-First Composition

  • Always render semantic HTML (<button>, <a>, <nav>, <main>) before reaching for role attributes
  • Every interactive element must be reachable by keyboard
  • Form inputs need labels — <label htmlFor> or aria-label if visually labeled by an icon
  • Manage focus on route changes and modal open/close
  • Run axe in component tests (see skills/react-testing)
  • Cross-link: skills/accessibility/SKILL.md covers WCAG criteria and pattern libraries

Routing

This skill is router-agnostic. The patterns above work with React Router, TanStack Router, Next.js App Router, Remix Router. Router-specific patterns (loaders, actions, nested layouts) follow the router's documentation — those are framework concerns layered on top of React core.

Out of Scope (Pointer Sections)

  • Next.js specifics: App Router data loading, Route Handlers, Middleware, Parallel Routes — separate concern, use Next.js docs
  • React Native: Platform-specific patterns differ enough to warrant a separate react-native-patterns skill (not present yet)
  • Remix: Loader/action conventions overlap with RSC but follow Remix docs
  • Rules: rules/react/ — coding-style, hooks, patterns, security, testing
  • Skills: react-performance for the Vercel-derived performance ruleset, frontend-patterns for cross-framework UI concerns, accessibility, angular-developer for framework comparison
  • Agents: react-reviewer for code review, react-build-resolver for build/bundler errors
  • Commands: /react-review, /react-build, /react-test

Examples

function useDebounce<T>(value: T, delay = 300): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);
  return debounced;
}

function SearchBox() {
  const [query, setQuery] = useState("");
  const debounced = useDebounce(query, 300);
  const { data } = useQuery({
    queryKey: ["search", debounced],
    queryFn: () => searchApi(debounced),
    enabled: debounced.length > 0,
  });
  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <Results items={data ?? []} />
    </>
  );
}

Optimistic UI with React 19 useOptimistic

"use client";
import { useOptimistic } from "react";

export function MessageList({ messages }: { messages: Message[] }) {
  const [optimistic, addOptimistic] = useOptimistic(
    messages,
    (state, newMessage: Message) => [...state, newMessage],
  );

  async function send(formData: FormData) {
    const text = String(formData.get("text"));
    addOptimistic({ id: "pending", text, sender: "me" });
    await saveMessage(text);
  }

  return (
    <>
      <ul>{optimistic.map((m) => <li key={m.id}>{m.text}</li>)}</ul>
      <form action={send}>
        <input name="text" />
        <button type="submit">Send</button>
      </form>
    </>
  );
}

Splitting context to avoid render cascades

// Two contexts: one rarely changes, one frequently
const ThemeContext = createContext<Theme>("light");
const NotificationsContext = createContext<Notification[]>([]);

// A component that only consumes ThemeContext does NOT re-render when notifications change