workleap-react-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWorkleap React Best Practices
Workleap React 最佳实践
Performance optimization guide for React Single Page Applications (SPA), tailored for Workleap's SPA-first architecture.
针对 Workleap 以 SPA 优先架构设计的 React 单页应用(SPA)性能优化指南。
When to Apply
适用场景
Reference these guidelines when:
- Writing new React components
- Reviewing code for performance issues
- Refactoring existing React code
- Optimizing bundle size or load times
- Debugging unnecessary re-renders
在以下场景参考本指南:
- 编写新的 React 组件
- 评审代码以排查性能问题
- 重构现有 React 代码
- 优化包体积或加载时间
- 调试不必要的重复渲染
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Reference |
|---|---|---|---|
| 1 | Eliminating Waterfalls | CRITICAL | async-rules.md |
| 2 | Bundle Size Optimization | CRITICAL | bundle-rules.md |
| 3 | Re-render Optimization | MEDIUM | rerender-rules.md |
| 4 | Rendering Performance | MEDIUM | rendering-rules.md |
| 5 | JavaScript Performance | LOW-MEDIUM | js-rules.md |
| 6 | Advanced Patterns | LOW | advanced-rules.md |
| 优先级 | 类别 | 影响程度 | 参考文档 |
|---|---|---|---|
| 1 | 消除异步瀑布 | 关键 | async-rules.md |
| 2 | 包体积优化 | 关键 | bundle-rules.md |
| 3 | 重复渲染优化 | 中等 | rerender-rules.md |
| 4 | 渲染性能优化 | 中等 | rendering-rules.md |
| 5 | JavaScript 性能优化 | 低-中等 | js-rules.md |
| 6 | 高级模式 | 低 | advanced-rules.md |
Quick Reference
快速参考
1. Eliminating Waterfalls (CRITICAL)
1. 消除异步瀑布(关键)
Waterfalls are the #1 performance killer. Each sequential await adds full network latency.
- Defer Await Until Needed - Move await into branches where actually used
- Promise.all() for Independent Operations - Run independent async operations concurrently
- Dependency-Based Parallelization - Use promise chaining for partial dependencies
- Prevent Waterfall Chains - Start promises early, await late
Read references/async-rules.md for detailed rules and code examples.
异步瀑布是头号性能杀手。每个顺序执行的 await 都会增加完整的网络延迟。
- 延迟 await 至需要时 - 将 await 移至实际需要使用的代码分支中
- Promise.all() 处理独立操作 - 并发执行独立的异步操作
- 基于依赖的并行化 - 使用 promise 链式调用处理部分依赖关系
- 避免瀑布链 - 尽早启动 promise,延迟 await 时机
查看 references/async-rules.md 获取详细规则及代码示例。
2. Bundle Size Optimization (CRITICAL)
2. 包体积优化(关键)
Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
- Route-Based Code Splitting - Lazy-load each route so users only download code they visit
- Avoid Barrel File Imports - Import directly from source files, not barrel re-exports
- React.lazy for Heavy Components - Lazy-load large components not needed on initial render
- Conditional Module Loading - Load modules only when feature is activated
- Preload on User Intent - Preload heavy bundles on hover/focus
Read references/bundle-rules.md for detailed rules and code examples.
减小初始包体积可提升交互时间(Time to Interactive)和最大内容绘制(Largest Contentful Paint)指标。
- 基于路由的代码分割 - 懒加载每个路由,让用户仅下载其访问页面的代码
- 避免桶文件导入 - 直接从源文件导入,而非通过桶文件重新导出
- React.lazy 处理重型组件 - 懒加载初始渲染不需要的大型组件
- 条件式模块加载 - 仅在功能激活时加载对应模块
- 基于用户意图预加载 - 在用户悬停/聚焦时预加载重型包
查看 references/bundle-rules.md 获取详细规则及代码示例。
3. Re-render Optimization (MEDIUM)
3. 重复渲染优化(中等)
Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
- Defer State Reads - Don't subscribe to state only used in callbacks
- Extract to Memoized Components - Enable early returns before computation
- Hoist Default Non-primitive Props - Extract default values to constants for stable memo
- Narrow Effect Dependencies - Use primitive dependencies in effects
- Subscribe to Derived State - Subscribe to derived booleans, not raw values
- Calculate Derived State During Render - Derive state during render, not effects
- Functional setState - Use functional setState for stable callbacks
- Lazy State Initialization - Pass function to useState for expensive values
- Skip useMemo for Simple Expressions - Avoid memo for simple primitives
- Put Logic in Event Handlers - Put interaction logic in event handlers, not effects
- Transitions for Non-Urgent Updates - Use startTransition for non-urgent updates
- useRef for Transient Values - Use refs for transient frequent values
Read references/rerender-rules.md for detailed rules and code examples.
减少不必要的重复渲染可最大限度减少计算浪费,提升 UI 响应速度。
- 延迟状态读取 - 不要订阅仅在回调中使用的状态
- 提取为记忆化组件 - 在计算前启用提前返回
- 提升非原始类型默认属性 - 将默认值提取为常量以实现稳定的记忆化
- 缩小 Effect 依赖范围 - 在 effects 中使用原始类型依赖
- 订阅派生状态 - 订阅派生的布尔值,而非原始值
- 在渲染期间计算派生状态 - 在渲染期间而非 effects 中派生状态
- 函数式 setState - 使用函数式 setState 以获得稳定的回调
- 懒加载状态初始化 - 向 useState 传递函数以处理昂贵的初始值
- 简单表达式跳过 useMemo - 避免对简单原始值使用记忆化
- 将逻辑放在事件处理函数中 - 将交互逻辑放在事件处理函数而非 effects 中
- 非紧急更新使用 Transitions - 对非紧急更新使用 startTransition
- 瞬时值使用 useRef - 对频繁变化的瞬时值使用 refs
查看 references/rerender-rules.md 获取详细规则及代码示例。
4. Rendering Performance (MEDIUM)
4. 渲染性能优化(中等)
Optimizing the rendering process reduces the work the browser needs to do.
- Animate SVG Wrapper - Animate div wrapper, not SVG element
- CSS content-visibility - Use content-visibility for long lists
- Hoist Static JSX - Extract static JSX outside components
- Optimize SVG Precision - Reduce SVG coordinate precision
- Activity Component (Experimental) - Use Activity for show/hide with state preservation
- Explicit Conditional Rendering - Use ternary, not && for conditionals
- useTransition for Loading - Prefer useTransition over manual loading state
Read references/rendering-rules.md for detailed rules and code examples.
优化渲染过程可减少浏览器需要处理的工作量。
- 动画 SVG 外层容器 - 为 div 外层容器添加动画,而非直接动画 SVG 元素
- CSS content-visibility - 对长列表使用 content-visibility 属性
- 提升静态 JSX - 将静态 JSX 提取到组件外部
- 优化 SVG 精度 - 降低 SVG 坐标精度
- Activity 组件(实验性) - 使用 Activity 组件实现带状态保留的显示/隐藏
- 显式条件渲染 - 使用三元表达式而非 && 进行条件渲染
- 加载状态使用 useTransition - 优先使用 useTransition 而非手动管理加载状态
查看 references/rendering-rules.md 获取详细规则及代码示例。
5. JavaScript Performance (LOW-MEDIUM)
5. JavaScript 性能优化(低-中等)
Micro-optimizations for hot paths that can add up to meaningful improvements.
- Avoid Layout Thrashing - Batch DOM writes, avoid interleaved reads
- Build Index Maps - Use Map for repeated lookups
- Cache Property Access - Cache object properties in loops
- Cache Function Results - Cache repeated function calls in module-level Map
- Cache Storage API Calls - Cache localStorage/sessionStorage reads
- Combine Array Iterations - Combine multiple filter/map into one loop
- Early Length Check - Check array length before expensive comparison
- Early Return - Return early from functions
- Hoist RegExp - Hoist RegExp creation outside loops
- Loop for Min/Max - Use loop instead of sort for min/max
- Set/Map Lookups - Use Set/Map for O(1) lookups
- toSorted() Immutability - Use toSorted() to prevent mutation bugs
Read references/js-rules.md for detailed rules and code examples.
针对热点路径的微优化,累积后可带来显著提升。
- 避免布局抖动 - 批量执行 DOM 写入操作,避免读写交错
- 构建索引映射 - 使用 Map 处理重复查找
- 缓存属性访问 - 在循环中缓存对象属性
- 缓存函数结果 - 在模块级 Map 中缓存重复函数调用结果
- 缓存 Storage API 调用 - 缓存 localStorage/sessionStorage 读取结果
- 合并数组迭代 - 将多个 filter/map 操作合并为单次循环
- 提前检查长度 - 在执行昂贵比较前检查数组长度
- 提前返回 - 从函数中提前返回
- 提升正则表达式 - 将正则表达式创建移至循环外部
- 循环查找最大/最小值 - 使用循环而非排序来查找最大/最小值
- Set/Map 查找 - 使用 Set/Map 实现 O(1) 时间复杂度的查找
- toSorted() 不可变性 - 使用 toSorted() 避免突变 bug
查看 references/js-rules.md 获取详细规则及代码示例。
6. Advanced Patterns (LOW)
6. 高级模式(低)
Advanced patterns for specific cases that require careful implementation.
- Event Handler Refs - Store event handlers in refs for stable subscriptions
- Initialize Once - Initialize app once per load, not per mount
- Stable Callback Refs - Stable callback refs for effects without re-runs
Read references/advanced-rules.md for detailed rules and code examples.
针对特定场景的高级模式,需谨慎实现。
- 事件处理函数 Refs - 将事件处理函数存储在 refs 中以实现稳定订阅
- 初始化一次 - 每个加载周期仅初始化应用一次,而非每次挂载
- 稳定回调 Refs - 使用稳定的回调 Refs 避免 effects 重复执行
查看 references/advanced-rules.md 获取详细规则及代码示例。