AgentSkillsCN

React Patterns

React 模式

SKILL.md

React Patterns Skill

React 18 + TypeScript standards and best practices.

When to Apply

  • Creating new React components
  • Implementing custom hooks
  • State management decisions
  • Performance optimization
  • Code review for React code

Component Standards

Component Structure Rules

RuleDescription
Functional onlyUse function components, no class components
TypeScript propsDefine Props interface for all components
Single responsibilityOne component = one purpose
Max 200 linesSplit larger components into sub-components

Component Organization

SectionOrder
1. ImportsTypes first, then libraries, then local
2. Props interfaceDefine before component
3. HooksAll hooks at top of function
4. HandlersEvent handlers after hooks
5. EffectsuseEffect after handlers
6. ReturnJSX at the end

Hook Standards

Built-in Hooks Usage

HookUse WhenAvoid When
useStateLocal component stateShared state (use Zustand)
useEffectSide effects, subscriptionsDerived state (use useMemo)
useMemoExpensive calculationsSimple values
useCallbackCallbacks passed to childrenInline handlers
useRefDOM refs, mutable valuesState that triggers renders

Custom Hook Guidelines

GuidelineDescription
Prefix with useuseFeatureName, useDataFetching
Return object{ data, loading, error }
Single responsibilityOne hook = one purpose
ReusableExtract when logic repeats 2+ times

TypeScript Requirements

Type Import Rules

RuleExample
Use import typeimport type { Props } from './types'
Use export typeexport type { ButtonProps }
Centralize typesAll types in types/index.ts
No anyUse unknown or proper types

Props Typing Standards

StandardDescription
Interface for propsinterface Props { ... }
Optional with ?title?: string
Children explicitchildren: React.ReactNode
Events typedonClick: (e: React.MouseEvent) => void

Performance Standards

Memoization Guidelines

TechniqueWhen to Use
useMemoExpensive calculations, derived data
useCallbackFunctions passed as props to memoized children
React.memoComponents with same props render same output

Re-render Prevention

CauseSolution
New object in propsMemoize with useMemo
New function in propsMemoize with useCallback
Context changesSplit contexts by update frequency
Parent re-rendersUse React.memo on child

Effect Guidelines

useEffect Rules

RuleDescription
Cleanup requiredReturn cleanup function for subscriptions
Dependency arrayInclude all referenced values
Avoid objects in depsUse primitive values or useMemo
No async directlyDefine async function inside effect

Common Effect Patterns

PatternUse Case
Data fetchingFetch on mount or dependency change
SubscriptionEvent listeners, WebSocket
DOM measurementRead layout after render
Sync externalSync state with external system

Event Handling Standards

Event Handler Naming

PatternExample
Action verbhandleClick, handleSubmit
Specific actionhandleDeleteItem, handleToggleMenu
Props callbackonAction, onChange

Event Types

EventType
ClickReact.MouseEvent<HTMLButtonElement>
ChangeReact.ChangeEvent<HTMLInputElement>
SubmitReact.FormEvent<HTMLFormElement>
KeyboardReact.KeyboardEvent

File Organization

Directory Structure

code
src/
├── components/
│   ├── common/          # Shared/reusable components
│   ├── [feature]/       # Feature-specific components
│   └── layout/          # Layout components
├── hooks/
│   └── use[Name].ts     # Custom hooks
├── pages/
│   └── [Page].tsx       # Route pages
├── services/
│   └── [name]Service.ts # API services
├── stores/
│   └── [name]Store.ts   # Zustand stores
└── types/
    └── index.ts         # All type definitions

Anti-Patterns to Avoid

Anti-PatternProblemSolution
useEffect for derived stateExtra rendersUse useMemo
Missing dependenciesStale closures, bugsAdd all deps
Index as keyBugs on reorderUse unique id
Prop drilling > 2 levelsHard to maintainUse Context/Zustand
Inline object propsNew reference each renderMemoize or extract
State for constantsUnnecessary complexityDefine outside component

Code Review Checklist

Component Review

  • Single responsibility principle followed
  • Props interface defined with TypeScript
  • No prop drilling beyond 2 levels
  • Hooks at top level only
  • Cleanup in useEffect where needed

Performance Review

  • Expensive calculations memoized
  • Callbacks memoized when passed to children
  • No new objects/arrays created in render
  • Keys are unique and stable

TypeScript Review

  • import type used for type imports
  • No any types
  • Props properly typed
  • Event handlers typed