agentleFS
Lukk17Lukk17/agent-standards/.agents/skills/react-patterns/SKILL.md

react-patterns

Skill1 starsChanged 56 days agoMITView on GitHub

React patterns for component composition, custom hooks, async state, a typed API client, memoisation, code splitting, virtualisation, forms, and animation. Use when you say "build a React component", "write a custom hook", "this list re-renders on every keystroke", "lazy load this chart", or "animate this list on mount". Not for Next.js rendering, routing, and caching, use `nextjs-app-router-patterns`.

29 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use typescript-strict, fastapi-patterns and 3 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • kevinaimonsterSkill

    typescript-strict

    TypeScript strict mode and advanced type system assistant. Helps write strictly-typed TypeScript code with generics, type guards, utility types, conditional types, mapped types, and template literal types. Trigger when user says 'TypeScript types' 'type gymnastics' 'TypeScript generics' 'strict TypeScript' 'type guard' 'TS类型' 'TypeScript严格模式' '类型体操' '泛型怎么写' 'TS type help'. Keywords: TypeScript, strict mode, generics, type guard, utility types, conditional types, mapped types, template literal types, infer, extends, keyof, typeof, type narrowing, discriminated unions, type assertion, type predicate, type gymnastics, TS, 类型体操, 泛型, 类型守卫, 严格类型

    Also in 3 projects that use this

  • hieutrtrSkill

    fastapi-patterns

    FastAPI framework mechanics and advanced patterns. Use when configuring middleware, creating dependency injection chains, implementing WebSocket endpoints, customizing OpenAPI documentation, setting up CORS, building authentication dependencies (JWT validation, role-based access), implementing background tasks, or managing application lifespan (startup/shutdown). Does NOT cover basic endpoint CRUD or repository/service patterns (use python-backend-expert) or testing (use pytest-patterns).

    Also in 3 projects that use this

  • AnthropicSkill

    testing-strategy

    Design test strategies and test plans. Trigger with "how should we test", "test strategy for", "write tests for", "test plan", "what tests do we need", or when the user needs help with testing approaches, coverage, or test architecture.

    Also in 4 projects that use this

  • rohitg00Skill

    django-patterns

    Django architecture patterns including DRF, ORM optimization, signals, middleware, and project structure

    Also in 3 projects that use this

  • MicrosoftSkill

    error-handling

    统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。

    Also in 4 projects that use this

The file

We split this skill into the rules it gives an agent

10 rules. 0 are common, 5 are distinctive, and 5 are very specific to this project.

  • 0

    Common

    Most of the 25 edited versions we read keep these.

  • 5

    Distinctive

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Default to none. A doc comment is usually a sign that the code failed to explain itself.

    line 188
  2. Distinctive:

    When one is still genuinely needed, the prose is capped at five lines and is usually one.

    line 193
  3. Distinctive:

    Every top-level component is a named function declaration, except an error boundary, which React supports only as a class component.

    line 248
  4. Very specific:

    Every async operation exposes one AsyncState union, not separate data, loading, and error flags.

    line 251
  5. Very specific:

    No component or hook calls fetch directly, and every endpoint lives in the typed API client.

    line 252
  6. Very specific:

    Every useMemo, useCallback, and React.memo traces back to a measurement.

    line 253
  7. Distinctive:

    No sort, splice, or reverse mutates a prop or a state value in place.

    line 254
  8. Distinctive:

    Every user-facing string goes through the i18n layer.

    line 256
  9. Very specific:

    Every animation respects prefers-reduced-motion.

    line 257
  10. Very specific:

    No doc comment restates a signature, and every recoverable error is documented with @throws.

    line 258

“Common” is measured: kept by at least 6 in 10 of the 25 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

React Development Patterns

React patterns for maintainable, performant user interfaces, covering composition, hooks, async state, data access, performance, forms, and animation. Everything here is framework-agnostic React that works the same inside or outside a meta-framework.

Baseline: React 19 with TypeScript. Server Components, streaming, and route-level caching belong to nextjs-app-router-patterns, and this skill defers to it on all three.


When to activate

  • Building React components: composition, props, rendering, compound components.
  • Managing state with useState, useReducer, Context, or a store such as Zustand.
  • Implementing client-side data fetching with SWR, React Query, or a typed API client.
  • Optimising rendering: memoisation, virtualisation, code splitting.
  • Working with forms: validation, controlled inputs, schema parsing.
  • Handling client-side routing and navigation.
  • Adding animation to a React interface.

When not to activate

  • Server Components, streaming, route caching, Server Actions, route handlers. Use nextjs-app-router-patterns.
  • Visual direction, typography, composition, and motion direction. Use frontend-design.
  • Tokens, theming, and stylesheet architecture. Use design-system.
  • WCAG conformance, ARIA semantics, and screen-reader behaviour. Use web-accessibility.
  • Angular components, signals, and RxJS. Use angular.
  • Profiling and Core Web Vitals work beyond React-level fixes. Use performance-optimization.

Reference map

TaskOpen
Context and reducer stores, custom state hooks, debouncingreferences/state-management.md
The typed API client, async data hooks, render props loadersreferences/data-fetching.md
Controlled forms, validation, error boundaries, i18n wiringreferences/forms.md
Animation with motion/react, reduced motion, timing budgetsreferences/animation.md
Keyboard navigation and focus management in Reactreferences/accessibility.md

Declare components as named functions

Named declarations hoist, give clearer stack traces and DevTools names, and read consistently across a file. Reserve arrow functions for callbacks and inline handlers.

// PASS: named declaration, name survives into DevTools and stack traces
export function MarketCard({ market }: MarketCardProps) {
  return <article className="market-card">{market.name}</article>
}

// FAIL: anonymous arrow assigned to a const, worse traces and no hoisting
export const MarketCard = ({ market }: MarketCardProps) => (
  <article className="market-card">{market.name}</article>
)

Compose components, never inherit

Build a family of small pieces that slot into each other. Inheritance in React produces components with a props surface that only grows. Error boundaries are the one exception, because React supports them only as class components.

// PASS: composed pieces, each with one job
export function Card({ children, variant = 'default' }: CardProps) {
  return <div className={`card card-${variant}`}>{children}</div>
}
export function CardHeader({ children }: { children: React.ReactNode }) {
  return <div className="card-header">{children}</div>
}

// FAIL: one component branching on flags for every caller
export function Card({ children, isHeader, isBody, isOutlined, isCompact, hasIcon }: EverythingProps) { ... }

Compound components (Tabs, Accordion, Menu) share state through a context created by the parent. The full pattern is in references/state-management.md.


Model async state as one discriminated union

Three loose flags let impossible combinations exist: loading and error and data all set at once. One union value makes those unrepresentable, and callers switch on state.status.

// PASS: one value, impossible states cannot be constructed
type AsyncState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; reason: Error }

// FAIL: three flags that can contradict each other
const [data, setData] = useState<T | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<Error | null>(null)

Route every network call through one typed API client

The base URL, the headers, the auth, and the response typing belong in one module. Components and hooks call the client, which keeps endpoint strings out of the UI and makes an auth or base-URL change a one-file edit.

// PASS: the component asks the client for markets
const markets = await api.markets.list()

// FAIL: a URL, a status check, and an untyped body in a component
const res = await fetch('https://api.example.com/markets')
const markets = await res.json()

The client module itself is in references/data-fetching.md.


Memoise only what you measured

useMemo, useCallback, and React.memo each add a dependency array to maintain and a cache to hold, and a wrong dependency list is its own class of bug. Reaching for them reflexively on cheap work costs more than it saves. Note also that Array.prototype.sort mutates, so copy before sorting or you mutate a prop.

// PASS: a measured expensive transform, and a copy before sorting
const sortedMarkets = useMemo(() => [...markets].sort((a, b) => b.volume - a.volume), [markets])

// FAIL: memoising a string concatenation, and sorting the prop in place
const label = useMemo(() => `${market.name} (${market.id})`, [market])
const sorted = markets.sort((a, b) => b.volume - a.volume)

Load heavy modules lazily and virtualise long lists

A charting or 3D library in the entry bundle delays every route that does not use it. A list of thousands of rows renders thousands of DOM nodes the user will never scroll to.

// PASS: heavy component split behind Suspense, long list virtualised
const HeavyChart = lazy(() => import('./HeavyChart'))
const virtualizer = useVirtualizer({ count: markets.length, getScrollElement: () => parentRef.current })

// FAIL: the library ships to every route, and 10,000 cards mount at once
import { HeavyChart } from './HeavyChart'
{markets.map((market) => <MarketCard key={market.id} market={market} />)}

The full virtualisation and code-splitting examples are in references/data-fetching.md.


Send every user-facing string through the i18n layer

A literal in JSX is a string that cannot be translated and cannot be changed without a code edit. Every label, placeholder, button, and message is looked up by key.

// PASS: copy lives in the catalogue
<button type="submit">{t('common.save')}</button>

// FAIL: copy welded into the component
<button type="submit">Save</button>

Doc Comments

Default to none. A doc comment is usually a sign that the code failed to explain itself. Before writing one, extract the unclear block into a well-named component or hook, rename the props so they carry their own meaning, and tighten the types. Do that first and most doc comments have nothing left to say, which is the outcome you want. Code that explains itself cannot go stale, a comment can.

When one is still genuinely needed, the prose is capped at five lines and is usually one. Every tag line is capped at one line, @param and @returns and @throws alike, and only appears when it genuinely adds something: if the note does not fit on a single line, shorten it or drop the tag. Four rules decide what goes in.

  1. Prose. One sentence saying what it does, then only what a caller cannot infer from the signature. Nothing more.
  2. @param only when the name and the type do not already convey it, meaning units, nullability, a valid range, or who owns the argument afterwards. @param userId - The user identifier is noise, delete it, and never restate a type TypeScript already declares.
  3. @returns only when it is non-obvious.
  4. @throws always, for every error a caller can act on. TypeScript keeps throws out of the signature, so this one is genuinely contract rather than decoration.

Going past the five-line prose cap is allowed only when the contract genuinely cannot be stated in fewer lines, for example a documented state machine, an ordering requirement, or a concurrency guarantee. It is an exception you justify in review, not a budget to spend. The one-line cap on a tag line has no exception at all: shorten it or delete it.

// PASS: one sentence, then only what the signature cannot say
/**
 * Subscribes to live price updates for one market.
 *
 * @returns null until the first message arrives
 */
export function useMarketPrice(marketId: string): Price | null { ... }

// FAIL: restates the signature and the hook name
/**
 * Hook for market price.
 *
 * @param marketId - The market id
 * @returns The price
 */
export function useMarketPrice(marketId: string): Price | null { ... }

Related skills

  • nextjs-app-router-patterns owns Server Components, streaming, route caching, Server Actions, and route handlers. This skill does not cover them.
  • web-accessibility owns WCAG conformance, ARIA semantics, and screen-reader behaviour. The React mechanics for keyboard and focus are in references/accessibility.md, and the requirements are in web-accessibility.
  • frontend-design for visual direction and motion direction.
  • design-system for tokens, theming, and stylesheet architecture.
  • performance-optimization for profiling and Core Web Vitals work beyond React-level fixes.
  • e2e-testing for driving these components in a browser.
  • coding-standards for the shared engineering floor these patterns sit on.

Checklist

  • Every top-level component is a named function declaration, except an error boundary, which React supports only as a class component.
  • Component families are composed, not configured through a growing flag surface.
  • Every async operation exposes one AsyncState union, not separate data, loading, and error flags.
  • No component or hook calls fetch directly, and every endpoint lives in the typed API client.
  • Every useMemo, useCallback, and React.memo traces back to a measurement.
  • No sort, splice, or reverse mutates a prop or a state value in place.
  • Heavy client-only modules are lazy loaded, and lists past a few hundred rows are virtualised.
  • Every user-facing string goes through the i18n layer.
  • Every animation respects prefers-reduced-motion.
  • No doc comment restates a signature, and every recoverable error is documented with @throws.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.