react-architectural-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Architectural Patterns
React 架构模式
Architecture
架构
Component Types
组件类型
Server Components
Server Components
Default in React 19 - rendered on server only.
Use Cases:
- Data fetching from databases or APIs
- Accessing backend resources directly
- Keeping sensitive information on server
- Large dependencies that don't need client-side
Characteristics:
- Cannot use hooks (useState, useEffect, etc.)
- Cannot use browser APIs
- Can be async functions
- Better performance (less JavaScript to client)
React 19 中的默认类型——仅在服务器端渲染。
适用场景:
- 从数据库或 API 获取数据
- 直接访问后端资源
- 敏感信息保留在服务器端
- 无需在客户端运行的大型依赖包
特性:
- 无法使用 hooks(useState、useEffect 等)
- 无法使用浏览器 API
- 可以是异步函数
- 性能更优(传递到客户端的 JavaScript 更少)
Client Components
Client Components
Interactive components that run on client.
Use Cases:
- Components using React hooks
- Event listeners and interactivity
- Browser APIs (localStorage, geolocation, etc.)
- Custom hooks usage
Characteristics:
- Must be marked with 'use client' directive
- Can use all React hooks
- Re-render on state changes
- Increases client bundle size
在客户端运行的交互式组件。
适用场景:
- 使用 React hooks 的组件
- 事件监听器与交互功能
- 浏览器 API(localStorage、地理定位等)
- 自定义 hooks 的使用
特性:
- 必须标记 'use client' 指令
- 可以使用所有 React hooks
- 状态变化时会重新渲染
- 会增加客户端包体积
Composition Patterns
组合模式
Component Composition
组件组合
- Prefer composition over inheritance
- Use children prop for flexible layouts
- Compound components for related functionality
- Higher-order components (HOCs) for cross-cutting concerns
- Render props for dynamic behavior
- 优先使用组合而非继承
- 使用 children prop 实现灵活布局
- 复合组件用于关联功能
- 高阶组件(HOCs)用于横切关注点
- 渲染属性用于动态行为
State Management
状态管理
- Lift state up to common ancestor
- Use Context for deeply nested props
- External state manager (Zustand) for global state
- Server state manager (React Query) for API data
- Separate UI state from server state
- 将状态提升到共同的祖先组件
- 使用 Context 处理深层嵌套的 props
- 外部状态管理器(Zustand)用于全局状态
- 服务器状态管理器(React Query)用于 API 数据
- 将 UI 状态与服务器状态分离
Data Flow
数据流
- Unidirectional data flow (top-down)
- Props for component configuration
- Callbacks for child-to-parent communication
- Context for implicit prop threading
- 单向数据流(自上而下)
- Props 用于组件配置
- 回调函数用于子组件到父组件的通信
- Context 用于隐式属性传递
Design Patterns
设计模式
Container/Presenter
容器/展示组件
Separate data fetching from presentation.
Structure:
- Container: Handles data fetching and business logic (Server Component)
- Presenter: Pure presentation component (can be Client Component)
Benefits:
- Easier testing of presentation logic
- Better performance with Server Components
- Clear separation of concerns
将数据获取与展示逻辑分离。
结构:
- 容器组件: 处理数据获取和业务逻辑(Server Component)
- 展示组件: 纯展示型组件(可以是 Client Component)
优势:
- 展示逻辑更易于测试
- 结合 Server Components 提升性能
- 关注点分离清晰
Custom Hooks
自定义 Hooks
Extract reusable stateful logic.
Naming: Always prefix with 'use' (useAuth, useLocalStorage)
Guidelines:
- One responsibility per hook
- Return arrays for multiple values [value, setValue]
- Return objects for named values { data, error, isLoading }
- Document hook behavior and dependencies
提取可复用的有状态逻辑。
命名规则: 始终以 'use' 为前缀(useAuth、useLocalStorage)
指导原则:
- 每个钩子单一职责
- 多值返回使用数组 [value, setValue]
- 命名值返回使用对象 { data, error, isLoading }
- 记录钩子的行为和依赖项
Error Boundaries
错误边界
Catch and handle React errors gracefully.
Implementation:
- Wrap entire app or route segments
- Provide fallback UI for errors
- Log errors to monitoring service
- Use error.tsx in Next.js for route-level boundaries
优雅地捕获和处理 React 错误。
实现方式:
- 包裹整个应用或路由片段
- 为错误场景提供备用 UI
- 将错误记录到监控服务
- 在 Next.js 中使用 error.tsx 实现路由级错误边界
Suspense Boundaries
Suspense 边界
Handle async operations with loading states.
Usage:
- Wrap async Server Components
- Show loading fallback during data fetch
- Nest Suspense for granular loading states
- Use loading.tsx in Next.js for route-level loading
处理异步操作的加载状态。
使用方式:
- 包裹异步 Server Components
- 数据获取期间显示加载占位符
- 嵌套 Suspense 实现细粒度加载状态
- 在 Next.js 中使用 loading.tsx 实现路由级加载
Code Organization
代码组织
File Structure
文件结构
Component Files
组件文件
- - Main component
ComponentName.tsx - - Scoped styles (if needed)
ComponentName.module.css - - Component tests
ComponentName.test.tsx - - Storybook stories (if used)
ComponentName.stories.tsx - - Barrel export
index.ts
- - 主组件
ComponentName.tsx - - 作用域样式(如有需要)
ComponentName.module.css - - 组件测试
ComponentName.test.tsx - - Storybook 故事(如使用)
ComponentName.stories.tsx - - 桶导出
index.ts
Feature Structure
功能模块结构
features/feature-name/
├── components/ # Feature-specific components
├── hooks/ # Feature-specific hooks
├── types/ # TypeScript types
├── utils/ # Helper functions
└── index.ts # Public APIfeatures/feature-name/
├── components/ # 功能专属组件
├── hooks/ # 功能专属钩子
├── types/ # TypeScript 类型定义
├── utils/ # 辅助函数
└── index.ts # 公共 APIImport Organization
导入组织
Order:
- React and framework imports
- External library imports
- Internal module imports (using @/ alias)
- Relative imports
- Style imports
- Type imports (using 'import type')
顺序:
- React 和框架导入
- 外部库导入
- 内部模块导入(使用 @/ 别名)
- 相对路径导入
- 样式导入
- 类型导入(使用 'import type')
Performance
性能
Optimization Techniques
优化技巧
- Use React.memo for expensive pure components
- Implement useMemo for expensive calculations
- Use useCallback for stable function references
- Code splitting with dynamic imports
- Lazy load components not needed immediately
- Virtualize long lists (react-window, react-virtuoso)
- 对开销大的纯组件使用 React.memo
- 对开销大的计算使用 useMemo
- 对稳定函数引用使用 useCallback
- 使用动态导入实现代码分割
- 懒加载非立即需要的组件
- 虚拟化长列表(react-window、react-virtuoso)
Anti-Patterns
反模式
Avoid:
- Inline function definitions in JSX
- Creating objects/arrays in render
- Excessive use of Context causing re-renders
- Not memoizing context values
- Premature optimization without profiling
避免:
- 在 JSX 中内联函数定义
- 在渲染时创建对象/数组
- 过度使用 Context 导致不必要的重渲染
- 不对 Context 值进行 memo 化
- 未做性能分析就过早优化
Accessibility
可访问性
Requirements
要求
- Use semantic HTML elements
- Provide ARIA labels where needed
- Ensure keyboard navigation works
- Maintain proper heading hierarchy
- Sufficient color contrast ratios
- Screen reader friendly text alternatives
- 使用语义化 HTML 元素
- 必要时提供 ARIA 标签
- 确保键盘导航正常工作
- 保持正确的标题层级
- 足够的颜色对比度
- 提供适合屏幕阅读器的文本替代方案