react-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Patterns
React模式
Expert guidance for implementing modern React patterns using hooks, component composition, state management, and concurrent features.
关于使用hooks、组件组合、状态管理和并发特性实现现代React模式的专业指导。
Core Philosophy
核心原则
| Priority | Description |
|---|---|
| Component Composition | Build complex UIs from simple, reusable pieces |
| Separation of Concerns | Business logic in hooks, presentation in components |
| Explicit over Implicit | Clear data flow and state management |
| Performance | Minimize re-renders, optimize heavy computations |
| Accessibility | Build inclusive, keyboard-navigable interfaces |
| 优先级 | 描述 |
|---|---|
| 组件组合 | 通过简单、可复用的片段构建复杂UI |
| 关注点分离 | 业务逻辑在hooks中,展示逻辑在组件中 |
| 显式优于隐式 | 清晰的数据流和状态管理 |
| 性能 | 最小化重渲染,优化繁重计算 |
| 无障碍性 | 构建包容性、支持键盘导航的界面 |
Pattern Categories
模式分类
Component Composition Patterns
组件组合模式
| Pattern | Use Case | Example |
|---|---|---|
| Compound Components | Flexible component APIs with shared context | Accordion, Tabs, Menu |
| Render Props | Share logic between components | MouseTracker, Scroll position |
| Higher-Order Components | Wrap components to add functionality | withAuth, 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模式
| Hook | Purpose |
|---|---|
| Data fetching with loading/error states |
| Form state management with validation |
| Debounce rapidly changing values |
| Access previous value of state/prop |
| Persist state to localStorage |
See references/examples.md for implementations.
| Hook | 用途 |
|---|---|
| 带有加载/错误状态的数据请求 |
| 带校验的表单状态管理 |
| 对快速变化的值进行防抖处理 |
| 获取状态/属性的上一个值 |
| 将状态持久化到localStorage |
实现示例请查看 references/examples.md。
State Management Patterns
状态管理模式
| Type | When to Use | Examples |
|---|---|---|
| useState | Simple UI state | Toggles, form inputs, pagination |
| useReducer | Complex state logic | Multi-step forms, shopping cart |
| Context | Theme, auth, app-wide settings | User session, feature flags |
| URL State | Shareable/bookmarkable state | Filters, search params, tabs |
| Server State | API data (React Query/SWR) | User profiles, product catalogs |
| Global Store | Cross-feature coordination | Zustand/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
何时使用记忆化
| Tool | Use When |
|---|---|
| Expensive calculations (sorting, filtering large arrays) |
| Functions passed to memoized children or used in deps |
| Pure components that re-render often with same props |
| 工具 | 使用场景 |
|---|---|
| 昂贵计算(排序、过滤大型数组) |
| 传递给记忆化子组件或作为依赖项的函数 |
| 频繁重渲染但属性未变化的纯组件 |
Code Splitting Strategy
代码拆分策略
| Level | Implementation |
|---|---|
| Route-level | |
| Component-level | Heavy components like charts, editors |
| Conditional | Features behind feature flags |
Always wrap lazy components in with appropriate fallback.
<Suspense>| 层级 | 实现方式 |
|---|---|
| 路由级 | |
| 组件级 | 图表、编辑器等重型组件 |
| 条件级 | 功能开关后的特性 |
请始终将lazy组件包裹在中,并设置合适的加载占位内容。
<Suspense>Error Handling
错误处理
| Strategy | Scope |
|---|---|
| Error Boundaries | Component tree errors (class components) |
| try/catch | Async operations, event handlers |
| React Query onError | API 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
无障碍设计模式
| Requirement | Implementation |
|---|---|
| Focus Management | Return focus to trigger on modal close |
| Keyboard Navigation | Support Tab, Enter, Escape in interactive elements |
| ARIA Labels | Icon buttons, form inputs without visible labels |
| Semantic HTML | Use |
See references/examples.md for accessible modal implementation.
| 要求 | 实现方式 |
|---|---|
| 焦点管理 | 模态框关闭时将焦点返回触发元素 |
| 键盘导航 | 交互元素支持Tab、Enter、Escape键 |
| ARIA标签 | 图标按钮、无可见标签的表单输入 |
| 语义化HTML | 合理使用 |
无障碍模态框实现示例请查看 references/examples.md。
Best Practices Checklist
最佳实践检查清单
- Extract custom hooks when logic is reused or complex (>20 lines)
- Use compound components for flexible component APIs
- Memoize expensive computations and callbacks passed to memoized children
- Code split routes and heavy components
- Handle errors with error boundaries at appropriate levels
- Manage focus in modals and dynamic content
- Use semantic HTML and ARIA labels for accessibility
- Test hooks in isolation from components
- Keep components small (< 200 lines)
- Colocate state with its usage
- 提取自定义hooks:当逻辑被复用或过于复杂(超过20行)时
- 使用复合组件:构建灵活的组件API
- 记忆化处理:对昂贵计算和传递给记忆化子组件的回调进行记忆化
- 代码拆分:对路由和重型组件进行拆分
- 错误处理:在合适层级使用错误边界
- 焦点管理:在模态框和动态内容中管理焦点
- 无障碍支持:使用语义化HTML和ARIA标签
- 独立测试hooks:与组件分离测试hooks
- 保持组件小巧:组件代码不超过200行
- 状态就近管理:将状态放在使用它的位置附近