react-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Best Practices

React最佳实践

Comprehensive performance optimization guide for React applications, adapted from Vercel Engineering. Contains 30 rules across 7 categories, prioritized by impact to guide automated refactoring and code generation.
Note: This version has been customized for pure React 19.2:
  • Server-side data fetching and SWR rules removed (project uses react-query)
  • Next.js-specific rules removed (next/dynamic, SSR hydration, etc.)
  • React Compiler is enabled - Memoization rules (
    memo
    ,
    useMemo
    ,
    useCallback
    ) removed as the compiler handles this automatically
这是一份改编自Vercel工程团队的React应用综合性能优化指南,包含7个类别下的30条规则,按影响优先级排序,用于指导自动化重构和代码生成。
注意:本版本已针对纯React 19.2进行定制:
  • 移除了服务端数据获取和SWR相关规则(项目使用react-query)
  • 移除了Next.js特定规则(如next/dynamic、SSR水合等)
  • 已启用React Compiler - 移除了记忆化规则(
    memo
    useMemo
    useCallback
    ),因为这些会由编译器自动处理

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
在以下场景中参考本指南:
  • 编写新的React组件时
  • 审查代码以排查性能问题时
  • 重构现有React代码时
  • 优化包体积或加载时长时

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Eliminating WaterfallsCRITICAL
async-
2Bundle Size OptimizationCRITICAL
bundle-
3Client-Side PatternsMEDIUM-HIGH
client-
4Re-render OptimizationMEDIUM
rerender-
5Rendering PerformanceMEDIUM
rendering-
6JavaScript PerformanceLOW-MEDIUM
js-
7Advanced PatternsLOW
advanced-
优先级类别影响程度前缀
1消除请求瀑布关键
async-
2包体积优化关键
bundle-
3客户端模式中高
client-
4重渲染优化中等
rerender-
5渲染性能中等
rendering-
6JavaScript性能低中
js-
7进阶模式
advanced-

Quick Reference

快速参考

1. Eliminating Waterfalls (CRITICAL)

1. 消除请求瀑布(关键)

  • async-defer-await
    - Move await into branches where actually used
  • async-parallel
    - Use Promise.all() for independent operations
  • async-suspense-boundaries
    - Use Suspense to stream content
  • async-defer-await
    - 将await移至实际需要使用的分支中
  • async-parallel
    - 对独立操作使用Promise.all()
  • async-suspense-boundaries
    - 使用Suspense流式传输内容

2. Bundle Size Optimization (CRITICAL)

2. 包体积优化(关键)

  • bundle-barrel-imports
    - Import directly, avoid barrel files
  • bundle-conditional
    - Load modules only when feature is activated
  • bundle-preload
    - Preload on hover/focus for perceived speed
  • bundle-barrel-imports
    - 直接导入,避免使用桶文件
  • bundle-conditional
    - 仅在功能激活时加载模块
  • bundle-preload
    - 在 hover/focus 时预加载以提升感知速度

3. Client-Side Patterns (MEDIUM-HIGH)

3. 客户端模式(中高)

  • client-localstorage-schema
    - Type-safe localStorage access
  • client-passive-event-listeners
    - Use passive event listeners for scroll/touch
  • client-localstorage-schema
    - 类型安全的localStorage访问
  • client-passive-event-listeners
    - 为滚动/触摸事件使用被动事件监听器

4. Re-render Optimization (MEDIUM)

4. 重渲染优化(中等)

  • rerender-defer-reads
    - Don't subscribe to state only used in callbacks
  • rerender-dependencies
    - Use primitive dependencies in effects
  • rerender-derived-state
    - Subscribe to derived booleans, not raw values
  • rerender-functional-setstate
    - Use functional setState for stable callbacks
  • rerender-lazy-state-init
    - Pass function to useState for expensive values
  • rerender-transitions
    - Use startTransition for non-urgent updates
  • rerender-defer-reads
    - 不要仅为回调函数订阅状态
  • rerender-dependencies
    - 在effect中使用原始类型依赖
  • rerender-derived-state
    - 订阅派生的布尔值,而非原始值
  • rerender-functional-setstate
    - 使用函数式setState以获得稳定的回调
  • rerender-lazy-state-init
    - 为昂贵的初始值向useState传入函数
  • rerender-transitions
    - 对非紧急更新使用startTransition

5. Rendering Performance (MEDIUM)

5. 渲染性能(中等)

  • rendering-animate-svg-wrapper
    - Animate div wrapper, not SVG element
  • rendering-content-visibility
    - Use content-visibility for long lists
  • rendering-svg-precision
    - Reduce SVG coordinate precision
  • rendering-activity
    - Use Activity component for show/hide
  • rendering-conditional-render
    - Use ternary, not && for conditionals
  • rendering-animate-svg-wrapper
    - 为div容器添加动画,而非SVG元素
  • rendering-content-visibility
    - 对长列表使用content-visibility
  • rendering-svg-precision
    - 降低SVG坐标精度
  • rendering-activity
    - 使用Activity组件实现显示/隐藏
  • rendering-conditional-render
    - 使用三元表达式而非&&进行条件渲染

6. JavaScript Performance (LOW-MEDIUM)

6. JavaScript性能(低中)

  • js-batch-dom-css
    - Group CSS changes via classes or cssText
  • js-index-maps
    - Build Map for repeated lookups
  • js-cache-property-access
    - Cache object properties in loops
  • js-cache-function-results
    - Cache function results in module-level Map
  • js-cache-storage
    - Cache localStorage/sessionStorage reads
  • js-combine-iterations
    - Combine multiple filter/map into one loop
  • js-length-check-first
    - Check array length before expensive comparison
  • js-early-exit
    - Return early from functions
  • js-hoist-regexp
    - Hoist RegExp creation outside loops
  • js-min-max-loop
    - Use loop for min/max instead of sort
  • js-set-map-lookups
    - Use Set/Map for O(1) lookups
  • js-tosorted-immutable
    - Use toSorted() for immutability
  • js-batch-dom-css
    - 通过类或cssText批量处理CSS变更
  • js-index-maps
    - 构建Map以支持重复查找
  • js-cache-property-access
    - 在循环中缓存对象属性
  • js-cache-function-results
    - 在模块级Map中缓存函数结果
  • js-cache-storage
    - 缓存localStorage/sessionStorage读取结果
  • js-combine-iterations
    - 将多个filter/map合并为单个循环
  • js-length-check-first
    - 在执行昂贵的比较前先检查数组长度
  • js-early-exit
    - 提前从函数返回
  • js-hoist-regexp
    - 将RegExp创建提升至循环外部
  • js-min-max-loop
    - 使用循环而非排序来获取最小值/最大值
  • js-set-map-lookups
    - 使用Set/Map实现O(1)时间复杂度的查找
  • js-tosorted-immutable
    - 使用toSorted()实现不可变操作

7. Advanced Patterns (LOW)

7. 进阶模式(低)

  • advanced-event-handler-refs
    - Store event handlers in refs
  • advanced-event-handler-refs
    - 将事件处理函数存储在refs中

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/async-parallel.md
rules/bundle-barrel-imports.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and references
阅读单个规则文件以获取详细说明和代码示例:
rules/async-parallel.md
rules/bundle-barrel-imports.md
每个规则文件包含:
  • 规则重要性的简要说明
  • 错误代码示例及解释
  • 正确代码示例及解释
  • 额外背景信息和参考资料

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需查看包含所有展开规则的完整指南,请查看:
AGENTS.md