react-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Patterns

React模式

Principles for building production-ready React applications.

构建生产级React应用的原则。

1. Component Design Principles

1. 组件设计原则

Component Types

组件类型

TypeUseState
ServerData fetching, staticNone
ClientInteractivityuseState, effects
PresentationalUI displayProps only
ContainerLogic/stateHeavy 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

PatternExtract When
useLocalStorageSame storage logic needed
useDebounceMultiple debounced values
useFetchRepeated fetch patterns
useFormComplex 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. 状态管理选型

ComplexitySolution
SimpleuseState, useReducer
Shared localContext
Server stateReact Query, SWR
Complex globalZustand, Redux Toolkit
复杂度解决方案
简单场景useState、useReducer
局部共享状态Context
服务端状态React Query、SWR
复杂全局状态Zustand、Redux Toolkit

State Placement

状态存放位置

ScopeWhere
Single componentuseState
Parent-childLift state up
SubtreeContext
App-wideGlobal store

作用域存放位置
单个组件useState
父子组件状态提升
组件子树Context
全局应用全局状态库

4. React 19 Patterns

4. React 19模式

New Hooks

新Hook

HookPurpose
useActionStateForm submission state
useOptimisticOptimistic UI updates
useRead 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 CasePrefer
Reusable logicCustom hook
Render flexibilityRender props
Cross-cuttingHigher-order component

使用场景优先选择
可复用逻辑自定义Hook
渲染灵活性Render Props
横切关注点高阶组件

6. Performance Principles

6. 性能优化原则

When to Optimize

何时优化

SignalAction
Slow rendersProfile first
Large listsVirtualize
Expensive calcuseMemo
Stable callbacksuseCallback
信号行动
渲染缓慢先进行性能分析
大型列表虚拟化处理
昂贵计算使用useMemo
稳定回调函数使用useCallback

Optimization Order

优化顺序

  1. Check if actually slow
  2. Profile with DevTools
  3. Identify bottleneck
  4. Apply targeted fix

  1. 确认是否真的存在性能问题
  2. 使用DevTools进行性能分析
  3. 定位性能瓶颈
  4. 应用针对性修复

7. Error Handling

7. 错误处理

Error Boundary Usage

错误边界的使用

ScopePlacement
App-wideRoot level
FeatureRoute/feature level
ComponentAround risky component
作用域放置位置
全局应用根组件层级
功能模块路由/功能层级
单个组件高风险组件周围

Error Recovery

错误恢复

  • Show fallback UI
  • Log error
  • Offer retry option
  • Preserve user data

  • 显示回退UI
  • 记录错误日志
  • 提供重试选项
  • 保留用户数据

8. TypeScript Patterns

8. TypeScript模式

Props Typing

Props类型定义

PatternUse
InterfaceComponent props
TypeUnions, complex
GenericReusable components
模式用途
Interface组件Props定义
Type联合类型、复杂类型
Generic可复用组件

Common Types

常用类型

NeedType
ChildrenReactNode
Event handlerMouseEventHandler
RefRefObject<Element>

需求类型
子元素ReactNode
事件处理器MouseEventHandler
引用RefObject<Element>

9. Testing Principles

9. 测试原则

LevelFocus
UnitPure functions, hooks
IntegrationComponent behavior
E2EUser flows
层级关注点
单元测试纯函数、Hook
集成测试组件行为
端到端测试用户流程

Test Priorities

测试优先级

  • User-visible behavior
  • Edge cases
  • Error states
  • Accessibility

  • 用户可见行为
  • 边缘情况
  • 错误状态
  • 可访问性

10. Anti-Patterns

10. 反模式

❌ Don't✅ Do
Prop drilling deepUse context
Giant componentsSplit smaller
useEffect for everythingServer components
Premature optimizationProfile first
Index as keyStable unique ID

Remember: React is about composition. Build small, combine thoughtfully.
❌ 避免✅ 推荐
深层Props透传使用Context
巨型组件拆分为小组件
所有逻辑都用useEffect实现使用服务端组件
过早优化先进行性能分析
使用索引作为key使用稳定唯一ID

谨记: React的核心是组件组合。构建小型组件,然后合理组合。