react

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Skill

React 技能

Modern React patterns using hooks, functional components, and best practices for building maintainable UIs with proper state management and performance optimization.
使用Hooks、函数式组件的现代React模式,以及构建可维护UI的最佳实践,包含合理的状态管理与性能优化方案。

When to Use

适用场景

Use when:
  • Creating or refactoring React functional components
  • Implementing hooks (useState, useEffect, useMemo, useCallback)
  • Managing state, side effects, or performance optimization
  • Building component composition patterns
Don't use for:
  • Non-React JS (use javascript skill)
  • React Native (use react-native skill)
  • Redux (use redux-toolkit skill)
  • Server-side frameworks (use astro or relevant framework skill)
适用于以下情况:
  • 创建或重构React函数式组件
  • 实现Hooks(useState、useEffect、useMemo、useCallback)
  • 状态管理、副作用处理或性能优化
  • 构建组件组合模式
不适用于:
  • 非React的JavaScript代码(使用JavaScript技能)
  • React Native(使用react-native技能)
  • Redux(使用redux-toolkit技能)
  • 服务端框架(使用astro或对应框架技能)

Critical Patterns

核心模式

Functional Components with Hooks

结合Hooks的函数式组件

typescript
// CORRECT: Functional component with hooks
const Counter: React.FC = () => {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
};

// WRONG: Class component (legacy)
class Counter extends React.Component {
  state = { count: 0 };
  render() { /* ... */ }
}
typescript
// CORRECT: Functional component with hooks
const Counter: React.FC = () => {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
};

// WRONG: Class component (legacy)
class Counter extends React.Component {
  state = { count: 0 };
  render() { /* ... */ }
}

Proper useEffect Dependencies

正确的useEffect依赖项

typescript
// CORRECT: All dependencies included
useEffect(() => {
  fetchData(userId);
}, [userId]);

// WRONG: Missing dependencies (stale closures)
useEffect(() => {
  fetchData(userId);
}, []); // userId missing
typescript
// CORRECT: All dependencies included
useEffect(() => {
  fetchData(userId);
}, [userId]);

// WRONG: Missing dependencies (stale closures)
useEffect(() => {
  fetchData(userId);
}, []); // userId missing

Stable Keys for Lists

列表的稳定Key

typescript
// CORRECT: Unique IDs
{items.map(item => <li key={item.id}>{item.name}</li>)}

// WRONG: Array index (bugs on reorder/delete)
{items.map((item, index) => <li key={index}>{item.name}</li>)}
typescript
// CORRECT: Unique IDs
{items.map(item => <li key={item.id}>{item.name}</li>)}

// WRONG: Array index (bugs on reorder/delete)
{items.map((item, index) => <li key={index}>{item.name}</li>)}

Never Conditionally Call Hooks

禁止条件式调用Hooks

typescript
// WRONG: Breaks React rules
if (condition) {
  const [value, setValue] = useState(0);
}

// CORRECT: Hooks at top level, conditional logic inside
const [value, setValue] = useState(0);
const shouldUse = condition ? value : defaultValue;
typescript
// WRONG: Breaks React rules
if (condition) {
  const [value, setValue] = useState(0);
}

// CORRECT: Hooks at top level, conditional logic inside
const [value, setValue] = useState(0);
const shouldUse = condition ? value : defaultValue;

Conventions

约定规范

Defer to
conventions
skill for code organization/naming and
a11y
skill for semantic HTML, keyboard navigation, and ARIA attributes.
代码组织/命名请遵循
conventions
技能,语义化HTML、键盘导航和ARIA属性请遵循
a11y
技能。

Decision Tree

决策树

  • Simple state (<3 values)? ->
    useState
    . See hooks-advanced.md (useState Patterns section).
  • Complex state (4+ related values)? ->
    useReducer
    . See hooks-advanced.md (useReducer Patterns section).
  • Side effect? ->
    useEffect
    with proper deps. See useEffect-patterns.md.
  • Data fetching? ->
    useEffect
    + AbortController. See useEffect-patterns.md (Async Patterns section).
  • Performance issue? -> Profile first with React DevTools. See performance.md.
  • Expensive computation? ->
    useMemo
    . See performance.md (useMemo section).
  • Callbacks to memoized children? ->
    useCallback
    . See performance.md (useCallback section).
  • Shared state across components? -> Context API or lift state. See context-patterns.md.
  • Compound component API? -> See context-patterns.md (Compound Components section).
  • Form with validation? -> Controlled components. See forms-state.md.
  • Multi-step form? -> Wizard pattern. See forms-state.md (Multi-Step Forms section).
  • File upload? -> Controlled input + File API. See forms-state.md (File Uploads section).
  • Large list (1000+)? -> Virtualization. See performance.md (List Rendering Optimization section).
  • Conditional rendering? ->
    &&
    for simple, ternary for if-else, early return for complex logic.
  • 简单状态(少于3个值)? -> 使用
    useState
    。详见hooks-advanced.md的useState模式章节。
  • 复杂状态(4个及以上关联值)? -> 使用
    useReducer
    。详见hooks-advanced.md的useReducer模式章节。
  • 处理副作用? -> 使用带有正确依赖项的
    useEffect
    。详见useEffect-patterns.md
  • 数据请求? ->
    useEffect
    + AbortController。详见useEffect-patterns.md的异步模式章节。
  • 性能问题? -> 先使用React DevTools进行性能分析。详见performance.md
  • 昂贵计算? -> 使用
    useMemo
    。详见performance.md的useMemo章节。
  • 向已记忆子组件传递回调? -> 使用
    useCallback
    。详见performance.md的useCallback章节。
  • 组件间共享状态? -> Context API或状态提升。详见context-patterns.md
  • 复合组件API? -> 详见context-patterns.md的复合组件章节。
  • 带验证的表单? -> 受控组件。详见forms-state.md
  • 多步骤表单? -> 向导模式。详见forms-state.md的多步骤表单章节。
  • 文件上传? -> 受控输入 + File API。详见forms-state.md的文件上传章节。
  • 大型列表(1000+条数据)? -> 虚拟化处理。详见performance.md的列表渲染优化章节。
  • 条件渲染? -> 简单场景用
    &&
    ,二选一用三元表达式,复杂逻辑用提前返回。

Example

示例

typescript
import { useState, useMemo } from 'react';

interface TodoProps {
  items: string[];
}

const TodoList: React.FC<TodoProps> = ({ items }) => {
  const [filter, setFilter] = useState('');

  const filteredItems = useMemo(() =>
    items.filter(item => item.toLowerCase().includes(filter.toLowerCase())),
    [items, filter]
  );

  return (
    <div>
      <input value={filter} onChange={(e) => setFilter(e.target.value)} />
      <ul>
        {filteredItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};
typescript
import { useState, useMemo } from 'react';

interface TodoProps {
  items: string[];
}

const TodoList: React.FC<TodoProps> = ({ items }) => {
  const [filter, setFilter] = useState('');

  const filteredItems = useMemo(() =>
    items.filter(item => item.toLowerCase().includes(filter.toLowerCase())),
    [items, filter]
  );

  return (
    <div>
      <input value={filter} onChange={(e) => setFilter(e.target.value)} />
      <ul>
        {filteredItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

Edge Cases

边缘情况

Stale closures in useEffect: Include all dependencies or use functional setState:
setState(prev => prev + 1)
.
useEffect cleanup: Return cleanup for subscriptions, timers, listeners to prevent leaks:
typescript
useEffect(() => {
  const timer = setInterval(() => {}, 1000);
  return () => clearInterval(timer);
}, []);
Ref vs State:
useRef
for values that don't trigger re-renders (DOM refs, mutable values).
useState
for values that update UI.
Batching: React batches setState in event handlers. In async code, use
flushSync
for immediate updates (rare).
Children prop: Use
React.ReactNode
type. For render props:
{(data) => <Component data={data} />}
.
Architecture patterns: Only apply Clean Architecture / SOLID when AGENTS.md specifies it, the codebase already uses domain/application/infrastructure folders, or the user requests it. See architecture-patterns SKILL.md and frontend-integration.md.
useEffect中的闭包过期问题: 声明所有依赖项,或使用函数式setState:
setState(prev => prev + 1)
useEffect清理: 为订阅、定时器、监听器返回清理函数以避免内存泄漏:
typescript
useEffect(() => {
  const timer = setInterval(() => {}, 1000);
  return () => clearInterval(timer);
}, []);
Ref vs State:
useRef
用于不需要触发重渲染的值(DOM引用、可变值)。
useState
用于需要更新UI的值。
批处理: React会在事件处理函数中批量处理setState。在异步代码中,如需立即更新可使用
flushSync
(罕见场景)。
Children属性: 使用
React.ReactNode
类型。对于渲染属性:
{(data) => <Component data={data} />}
架构模式: 仅当AGENTS.md指定、代码库已使用领域/应用/基础设施文件夹结构,或用户要求时,才应用整洁架构/SOLID原则。详见architecture-patterns SKILL.mdfrontend-integration.md

Checklist

检查清单

  • Functional components with hooks (no class components)
  • All useEffect dependencies declared
  • Stable keys on list items (unique IDs, not indices)
  • No conditional hook calls
  • Cleanup returned from useEffect for subscriptions/timers
  • useMemo/useCallback only where profiling shows need
  • Controlled inputs for forms with validation
  • Context split by update frequency to avoid unnecessary re-renders
  • 使用结合Hooks的函数式组件(无类组件)
  • 声明所有useEffect依赖项
  • 列表项使用稳定Key(唯一ID,而非索引)
  • 无条件式调用Hooks
  • useEffect返回订阅/定时器的清理函数
  • 仅在性能分析显示需要时使用useMemo/useCallback
  • 带验证的表单使用受控输入
  • Context按更新频率拆分以避免不必要的重渲染

Resources

资源