react-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Patterns

React模式

Expert guidance for implementing modern React patterns using hooks, component composition, state management, and concurrent features.
关于使用hooks、组件组合、状态管理和并发特性实现现代React模式的专业指导。

Core Philosophy

核心原则

PriorityDescription
Component CompositionBuild complex UIs from simple, reusable pieces
Separation of ConcernsBusiness logic in hooks, presentation in components
Explicit over ImplicitClear data flow and state management
PerformanceMinimize re-renders, optimize heavy computations
AccessibilityBuild inclusive, keyboard-navigable interfaces
优先级描述
组件组合通过简单、可复用的片段构建复杂UI
关注点分离业务逻辑在hooks中,展示逻辑在组件中
显式优于隐式清晰的数据流和状态管理
性能最小化重渲染,优化繁重计算
无障碍性构建包容性、支持键盘导航的界面

Pattern Categories

模式分类

Component Composition Patterns

组件组合模式

PatternUse CaseExample
Compound ComponentsFlexible component APIs with shared contextAccordion, Tabs, Menu
Render PropsShare logic between componentsMouseTracker, Scroll position
Higher-Order ComponentsWrap components to add functionalitywithAuth, withLoading
See references/examples.md for full code examples.
模式使用场景示例
Compound Components(复合组件)具备共享上下文的灵活组件API折叠面板(Accordion)、标签页(Tabs)、菜单(Menu)
Render Props(渲染属性)在组件间共享逻辑鼠标追踪器(MouseTracker)、滚动位置监听
Higher-Order Components(高阶组件)包装组件以添加功能权限校验(withAuth)、加载状态(withLoading)
完整代码示例请查看 references/examples.md

Custom Hooks Patterns

自定义Hooks模式

HookPurpose
useApi
Data fetching with loading/error states
useForm
Form state management with validation
useDebounce
Debounce rapidly changing values
usePrevious
Access previous value of state/prop
useLocalStorage
Persist state to localStorage
See references/examples.md for implementations.
Hook用途
useApi
带有加载/错误状态的数据请求
useForm
带校验的表单状态管理
useDebounce
对快速变化的值进行防抖处理
usePrevious
获取状态/属性的上一个值
useLocalStorage
将状态持久化到localStorage
实现示例请查看 references/examples.md

State Management Patterns

状态管理模式

TypeWhen to UseExamples
useStateSimple UI stateToggles, form inputs, pagination
useReducerComplex state logicMulti-step forms, shopping cart
ContextTheme, auth, app-wide settingsUser session, feature flags
URL StateShareable/bookmarkable stateFilters, search params, tabs
Server StateAPI data (React Query/SWR)User profiles, product catalogs
Global StoreCross-feature coordinationZustand/Redux for complex apps
Context + useReducer Pattern: Best for complex state with multiple actions that need to be shared across components. See references/examples.md.
类型使用场景示例
useState简单UI状态开关切换、表单输入、分页
useReducer复杂状态逻辑多步骤表单、购物车
Context主题、权限、全局设置用户会话、功能开关
URL状态可共享/可收藏的状态筛选条件、搜索参数、标签页
服务端状态API数据(React Query/SWR)用户资料、产品目录
全局状态库跨功能模块协调复杂应用使用Zustand/Redux
Context + useReducer模式:最适合需要在多个组件间共享的、包含多个动作的复杂状态。详情请查看 references/examples.md

Performance Optimization

性能优化

When to Use Memoization

何时使用记忆化

ToolUse When
useMemo
Expensive calculations (sorting, filtering large arrays)
useCallback
Functions passed to memoized children or used in deps
memo
Pure components that re-render often with same props
工具使用场景
useMemo
昂贵计算(排序、过滤大型数组)
useCallback
传递给记忆化子组件或作为依赖项的函数
memo
频繁重渲染但属性未变化的纯组件

Code Splitting Strategy

代码拆分策略

LevelImplementation
Route-level
lazy(() => import('./pages/Dashboard'))
Component-levelHeavy components like charts, editors
ConditionalFeatures behind feature flags
Always wrap lazy components in
<Suspense>
with appropriate fallback.
层级实现方式
路由级
lazy(() => import('./pages/Dashboard'))
组件级图表、编辑器等重型组件
条件级功能开关后的特性
请始终将lazy组件包裹在
<Suspense>
中,并设置合适的加载占位内容。

Error Handling

错误处理

StrategyScope
Error BoundariesComponent tree errors (class components)
try/catchAsync operations, event handlers
React Query onErrorAPI errors with automatic retry
Error Boundary Placement: App-level for fatal errors, feature-level for graceful degradation.
策略适用范围
错误边界(Error Boundaries)组件树错误(类组件)
try/catch异步操作、事件处理程序
React Query onError带自动重试的API错误
错误边界放置:应用级用于捕获致命错误,功能级用于实现优雅降级。

Accessibility Patterns

无障碍设计模式

RequirementImplementation
Focus ManagementReturn focus to trigger on modal close
Keyboard NavigationSupport Tab, Enter, Escape in interactive elements
ARIA LabelsIcon buttons, form inputs without visible labels
Semantic HTMLUse
<nav>
,
<main>
,
<button>
appropriately
See references/examples.md for accessible modal implementation.
要求实现方式
焦点管理模态框关闭时将焦点返回触发元素
键盘导航交互元素支持Tab、Enter、Escape键
ARIA标签图标按钮、无可见标签的表单输入
语义化HTML合理使用
<nav>
<main>
<button>
等标签
无障碍模态框实现示例请查看 references/examples.md

Best Practices Checklist

最佳实践检查清单

  1. Extract custom hooks when logic is reused or complex (>20 lines)
  2. Use compound components for flexible component APIs
  3. Memoize expensive computations and callbacks passed to memoized children
  4. Code split routes and heavy components
  5. Handle errors with error boundaries at appropriate levels
  6. Manage focus in modals and dynamic content
  7. Use semantic HTML and ARIA labels for accessibility
  8. Test hooks in isolation from components
  9. Keep components small (< 200 lines)
  10. Colocate state with its usage
  1. 提取自定义hooks:当逻辑被复用或过于复杂(超过20行)时
  2. 使用复合组件:构建灵活的组件API
  3. 记忆化处理:对昂贵计算和传递给记忆化子组件的回调进行记忆化
  4. 代码拆分:对路由和重型组件进行拆分
  5. 错误处理:在合适层级使用错误边界
  6. 焦点管理:在模态框和动态内容中管理焦点
  7. 无障碍支持:使用语义化HTML和ARIA标签
  8. 独立测试hooks:与组件分离测试hooks
  9. 保持组件小巧:组件代码不超过200行
  10. 状态就近管理:将状态放在使用它的位置附近