react-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Patterns
React模式
Principles for building production-ready React applications.
构建生产级React应用的原则。
1. Component Design Principles
1. 组件设计原则
Component Types
组件类型
| Type | Use | State |
|---|---|---|
| Server | Data fetching, static | None |
| Client | Interactivity | useState, effects |
| Presentational | UI display | Props only |
| Container | Logic/state | Heavy state |
| 类型 | 用途 | 状态 |
|---|---|---|
| 服务端组件 | 数据获取、静态展示 | 无 |
| 客户端组件 | 交互功能 | 使用useState、副作用 |
| 展示型组件 | UI展示 | 仅接收Props |
| 容器型组件 | 逻辑/状态管理 | 复杂状态 |
Design Rules
设计规则
- One responsibility per component
- Props down, events up
- Composition over inheritance
- Prefer small, focused components
- 单一组件单一职责
- Props向下传递,事件向上触发
- 优先组合而非继承
- 偏好小型、聚焦的组件
2. Hook Patterns
2. Hook模式
When to Extract Hooks
何时提取自定义Hook
| Pattern | Extract When |
|---|---|
| useLocalStorage | Same storage logic needed |
| useDebounce | Multiple debounced values |
| useFetch | Repeated fetch patterns |
| useForm | Complex form state |
| 模式 | 提取场景 |
|---|---|
| useLocalStorage | 需要重复使用相同的存储逻辑 |
| useDebounce | 存在多个防抖值需求 |
| useFetch | 重复出现的数据获取模式 |
| useForm | 复杂表单状态管理 |
Hook Rules
Hook规则
- Hooks at top level only
- Same order every render
- Custom hooks start with "use"
- Clean up effects on unmount
- 仅在顶层调用Hook
- 每次渲染保持相同的调用顺序
- 自定义Hook以"use"开头
- 组件卸载时清理副作用
3. State Management Selection
3. 状态管理选型
| Complexity | Solution |
|---|---|
| Simple | useState, useReducer |
| Shared local | Context |
| Server state | React Query, SWR |
| Complex global | Zustand, Redux Toolkit |
| 复杂度 | 解决方案 |
|---|---|
| 简单场景 | useState、useReducer |
| 局部共享状态 | Context |
| 服务端状态 | React Query、SWR |
| 复杂全局状态 | Zustand、Redux Toolkit |
State Placement
状态存放位置
| Scope | Where |
|---|---|
| Single component | useState |
| Parent-child | Lift state up |
| Subtree | Context |
| App-wide | Global store |
| 作用域 | 存放位置 |
|---|---|
| 单个组件 | useState |
| 父子组件 | 状态提升 |
| 组件子树 | Context |
| 全局应用 | 全局状态库 |
4. React 19 Patterns
4. React 19模式
New Hooks
新Hook
| Hook | Purpose |
|---|---|
| useActionState | Form submission state |
| useOptimistic | Optimistic UI updates |
| use | Read resources in render |
| Hook | 用途 |
|---|---|
| useActionState | 表单提交状态管理 |
| useOptimistic | 乐观UI更新 |
| use | 在渲染中读取资源 |
Compiler Benefits
编译器优势
- Automatic memoization
- Less manual useMemo/useCallback
- Focus on pure components
- 自动记忆化
- 减少手动使用useMemo/useCallback
- 专注于纯组件
5. Composition Patterns
5. 组件组合模式
Compound Components
复合组件
- Parent provides context
- Children consume context
- Flexible slot-based composition
- Example: Tabs, Accordion, Dropdown
- 父组件提供上下文
- 子组件消费上下文
- 灵活的插槽式组合
- 示例:Tabs、Accordion、Dropdown
Render Props vs Hooks
Render Props vs Hooks
| Use Case | Prefer |
|---|---|
| Reusable logic | Custom hook |
| Render flexibility | Render props |
| Cross-cutting | Higher-order component |
| 使用场景 | 优先选择 |
|---|---|
| 可复用逻辑 | 自定义Hook |
| 渲染灵活性 | Render Props |
| 横切关注点 | 高阶组件 |
6. Performance Principles
6. 性能优化原则
When to Optimize
何时优化
| Signal | Action |
|---|---|
| Slow renders | Profile first |
| Large lists | Virtualize |
| Expensive calc | useMemo |
| Stable callbacks | useCallback |
| 信号 | 行动 |
|---|---|
| 渲染缓慢 | 先进行性能分析 |
| 大型列表 | 虚拟化处理 |
| 昂贵计算 | 使用useMemo |
| 稳定回调函数 | 使用useCallback |
Optimization Order
优化顺序
- Check if actually slow
- Profile with DevTools
- Identify bottleneck
- Apply targeted fix
- 确认是否真的存在性能问题
- 使用DevTools进行性能分析
- 定位性能瓶颈
- 应用针对性修复
7. Error Handling
7. 错误处理
Error Boundary Usage
错误边界的使用
| Scope | Placement |
|---|---|
| App-wide | Root level |
| Feature | Route/feature level |
| Component | Around risky component |
| 作用域 | 放置位置 |
|---|---|
| 全局应用 | 根组件层级 |
| 功能模块 | 路由/功能层级 |
| 单个组件 | 高风险组件周围 |
Error Recovery
错误恢复
- Show fallback UI
- Log error
- Offer retry option
- Preserve user data
- 显示回退UI
- 记录错误日志
- 提供重试选项
- 保留用户数据
8. TypeScript Patterns
8. TypeScript模式
Props Typing
Props类型定义
| Pattern | Use |
|---|---|
| Interface | Component props |
| Type | Unions, complex |
| Generic | Reusable components |
| 模式 | 用途 |
|---|---|
| Interface | 组件Props定义 |
| Type | 联合类型、复杂类型 |
| Generic | 可复用组件 |
Common Types
常用类型
| Need | Type |
|---|---|
| Children | ReactNode |
| Event handler | MouseEventHandler |
| Ref | RefObject<Element> |
| 需求 | 类型 |
|---|---|
| 子元素 | ReactNode |
| 事件处理器 | MouseEventHandler |
| 引用 | RefObject<Element> |
9. Testing Principles
9. 测试原则
| Level | Focus |
|---|---|
| Unit | Pure functions, hooks |
| Integration | Component behavior |
| E2E | User flows |
| 层级 | 关注点 |
|---|---|
| 单元测试 | 纯函数、Hook |
| 集成测试 | 组件行为 |
| 端到端测试 | 用户流程 |
Test Priorities
测试优先级
- User-visible behavior
- Edge cases
- Error states
- Accessibility
- 用户可见行为
- 边缘情况
- 错误状态
- 可访问性
10. Anti-Patterns
10. 反模式
| ❌ Don't | ✅ Do |
|---|---|
| Prop drilling deep | Use context |
| Giant components | Split smaller |
| useEffect for everything | Server components |
| Premature optimization | Profile first |
| Index as key | Stable unique ID |
Remember: React is about composition. Build small, combine thoughtfully.
| ❌ 避免 | ✅ 推荐 |
|---|---|
| 深层Props透传 | 使用Context |
| 巨型组件 | 拆分为小组件 |
| 所有逻辑都用useEffect实现 | 使用服务端组件 |
| 过早优化 | 先进行性能分析 |
| 使用索引作为key | 使用稳定唯一ID |
谨记: React的核心是组件组合。构建小型组件,然后合理组合。