react-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Best Practices - Performance Optimization

React最佳实践 - 性能优化

Comprehensive performance optimization guide for React and Next.js applications with 40+ rules organized by impact level. Designed to help developers eliminate performance bottlenecks and follow best practices.
这是一份针对React和Next.js应用的全面性能优化指南,包含40+条按影响等级划分的规则,旨在帮助开发者消除性能瓶颈并遵循最佳实践。

When to use this skill

何时使用本指南

Use React Best Practices when:
  • Optimizing React or Next.js application performance
  • Reviewing code for performance improvements
  • Refactoring existing components for better performance
  • Implementing new features with performance in mind
  • Debugging slow rendering or loading issues
  • Reducing bundle size
  • Eliminating request waterfalls
Key areas covered:
  • Eliminating Waterfalls (CRITICAL): Prevent sequential async operations
  • Bundle Size Optimization (CRITICAL): Reduce initial JavaScript payload
  • Server-Side Performance (HIGH): Optimize RSC and data fetching
  • Client-Side Data Fetching (MEDIUM-HIGH): Implement efficient caching
  • Re-render Optimization (MEDIUM): Minimize unnecessary re-renders
  • Rendering Performance (MEDIUM): Optimize browser rendering
  • JavaScript Performance (LOW-MEDIUM): Micro-optimizations for hot paths
  • Advanced Patterns (LOW): Specialized techniques for edge cases
在以下场景使用React最佳实践:
  • 优化React或Next.js应用性能
  • 审查代码以提升性能
  • 重构现有组件以获得更好的性能
  • 开发新功能时考虑性能因素
  • 调试渲染缓慢或加载问题
  • 减小打包体积
  • 消除请求瀑布
核心覆盖领域:
  • 消除请求瀑布(CRITICAL):防止串行异步操作
  • 打包体积优化(CRITICAL):减少初始JavaScript负载
  • 服务端性能(HIGH):优化RSC和数据获取
  • 客户端数据获取(MEDIUM-HIGH):实现高效缓存
  • 重渲染优化(MEDIUM):最小化不必要的重渲染
  • 渲染性能(MEDIUM):优化浏览器渲染
  • JavaScript性能(LOW-MEDIUM):热点路径的微优化
  • 高级模式(LOW):针对边缘情况的专门技术

Quick reference

快速参考

Critical priorities

最高优先级事项

  1. Defer await until needed - Move awaits into branches where they're used
  2. Use Promise.all() - Parallelize independent async operations
  3. Avoid barrel imports - Import directly from source files
  4. Dynamic imports - Lazy-load heavy components
  5. Strategic Suspense - Stream content while showing layout
  1. 延迟await直到需要时 - 将await移至使用它的分支中
  2. 使用Promise.all() - 并行执行独立的异步操作
  3. 避免桶式导入 - 直接从源文件导入
  4. 动态导入 - 懒加载重型组件
  5. 策略性使用Suspense - 在显示布局的同时流式传输内容

Common patterns

常见模式

Parallel data fetching:
typescript
const [user, posts, comments] = await Promise.all([
  fetchUser(),
  fetchPosts(),
  fetchComments()
])
Direct imports:
tsx
// ❌ Loads entire library
import { Check } from 'lucide-react'

// ✅ Loads only what you need
import Check from 'lucide-react/dist/esm/icons/check'
Dynamic components:
tsx
import dynamic from 'next/dynamic'

const MonacoEditor = dynamic(
  () => import('./monaco-editor'),
  { ssr: false }
)
并行数据获取:
typescript
const [user, posts, comments] = await Promise.all([
  fetchUser(),
  fetchPosts(),
  fetchComments()
])
直接导入:
tsx
// ❌ 加载整个库
import { Check } from 'lucide-react'

// ✅ 仅加载所需内容
import Check from 'lucide-react/dist/esm/icons/check'
动态组件:
tsx
import dynamic from 'next/dynamic'

const MonacoEditor = dynamic(
  () => import('./monaco-editor'),
  { ssr: false }
)

Using the guidelines

指南使用方法

The complete performance guidelines are available in the references folder:
  • react-performance-guidelines.md: Complete guide with all 40+ rules, code examples, and impact analysis
Each rule includes:
  • Incorrect/correct code comparisons
  • Specific impact metrics
  • When to apply the optimization
  • Real-world examples
完整的性能指南可在参考文件夹中获取:
  • react-performance-guidelines.md:包含所有40+条规则、代码示例和影响分析的完整指南
每条规则都包含:
  • 错误/正确代码对比
  • 具体影响指标
  • 何时应用该优化
  • 真实场景示例

Categories overview

分类概述

1. Eliminating Waterfalls (CRITICAL)

1. 消除请求瀑布(CRITICAL)

Waterfalls are the #1 performance killer. Each sequential await adds full network latency.
  • Defer await until needed
  • Dependency-based parallelization
  • Prevent waterfall chains in API routes
  • Promise.all() for independent operations
  • Strategic Suspense boundaries
请求瀑布是头号性能杀手,每个串行await都会增加完整的网络延迟。
  • 延迟await直到需要时
  • 基于依赖的并行化
  • 防止API路由中的瀑布链
  • 对独立操作使用Promise.all()
  • 策略性设置Suspense边界

2. Bundle Size Optimization (CRITICAL)

2. 打包体积优化(CRITICAL)

Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
  • Avoid barrel file imports
  • Conditional module loading
  • Defer non-critical third-party libraries
  • Dynamic imports for heavy components
  • Preload based on user intent
减小初始打包体积可提升交互时间(TTI)和最大内容绘制(LCP)。
  • 避免桶式文件导入
  • 条件式模块加载
  • 延迟加载非关键第三方库
  • 动态导入重型组件
  • 根据用户意图预加载

3. Server-Side Performance (HIGH)

3. 服务端性能(HIGH)

Optimize server-side rendering and data fetching.
  • Cross-request LRU caching
  • Minimize serialization at RSC boundaries
  • Parallel data fetching with component composition
  • Per-request deduplication with React.cache()
优化服务端渲染和数据获取。
  • 跨请求LRU缓存
  • 最小化RSC边界处的序列化操作
  • 通过组件组合实现并行数据获取
  • 使用React.cache()实现单请求去重

4. Client-Side Data Fetching (MEDIUM-HIGH)

4. 客户端数据获取(MEDIUM-HIGH)

Automatic deduplication and efficient data fetching patterns.
  • Deduplicate global event listeners
  • Use SWR for automatic deduplication
自动去重和高效的数据获取模式。
  • 全局事件监听器去重
  • 使用SWR实现自动去重

5. Re-render Optimization (MEDIUM)

5. 重渲染优化(MEDIUM)

Reduce unnecessary re-renders to minimize wasted computation.
  • Defer state reads to usage point
  • Extract to memoized components
  • Narrow effect dependencies
  • Subscribe to derived state
  • Use lazy state initialization
  • Use transitions for non-urgent updates
减少不必要的重渲染以最小化无效计算。
  • 延迟状态读取至使用点
  • 提取为记忆化组件
  • 缩小effect依赖范围
  • 订阅派生状态
  • 使用惰性状态初始化
  • 对非紧急更新使用transitions

6. Rendering Performance (MEDIUM)

6. 渲染性能(MEDIUM)

Optimize the browser rendering process.
  • Animate SVG wrapper instead of SVG element
  • CSS content-visibility for long lists
  • Hoist static JSX elements
  • Optimize SVG precision
  • Prevent hydration mismatch without flickering
  • Use Activity component for show/hide
  • Use explicit conditional rendering
优化浏览器渲染流程。
  • 为SVG容器而非SVG元素添加动画
  • 对长列表使用CSS content-visibility
  • 提升静态JSX元素层级
  • 优化SVG精度
  • 在无闪烁的情况下防止 hydration 不匹配
  • 使用Activity组件实现显示/隐藏
  • 使用显式条件渲染

7. JavaScript Performance (LOW-MEDIUM)

7. JavaScript性能(LOW-MEDIUM)

Micro-optimizations for hot paths.
  • Batch DOM CSS changes
  • Build index maps for repeated lookups
  • Cache property access in loops
  • Cache repeated function calls
  • Cache storage API calls
  • Combine multiple array iterations
  • Early length check for array comparisons
  • Early return from functions
  • Hoist RegExp creation
  • Use loop for min/max instead of sort
  • Use Set/Map for O(1) lookups
  • Use toSorted() instead of sort()
热点路径的微优化。
  • 批量处理DOM CSS变更
  • 为重复查找构建索引映射
  • 在循环中缓存属性访问
  • 缓存重复函数调用
  • 缓存存储API调用
  • 合并多次数组迭代
  • 数组比较时提前检查长度
  • 函数提前返回
  • 将RegExp创建提升至外部
  • 使用循环而非排序来获取最小/最大值
  • 使用Set/Map实现O(1)查找
  • 使用toSorted()替代sort()

8. Advanced Patterns (LOW)

8. 高级模式(LOW)

Specialized techniques for edge cases.
  • Store event handlers in refs
  • useLatest for stable callback refs
针对边缘情况的专门技术。
  • 将事件处理函数存储在refs中
  • 使用useLatest获取稳定的回调refs

Implementation approach

实施步骤

When optimizing a React application:
  1. Profile first: Use React DevTools Profiler and browser performance tools to identify bottlenecks
  2. Focus on critical paths: Start with eliminating waterfalls and reducing bundle size
  3. Measure impact: Verify improvements with metrics (LCP, TTI, FID)
  4. Apply incrementally: Don't over-optimize prematurely
  5. Test thoroughly: Ensure optimizations don't break functionality
优化React应用时:
  1. 先分析:使用React DevTools Profiler和浏览器性能工具识别瓶颈
  2. 聚焦关键路径:从消除请求瀑布和减小打包体积开始
  3. 衡量影响:通过指标(LCP、TTI、FID)验证优化效果
  4. 逐步应用:不要过早过度优化
  5. 充分测试:确保优化不会破坏功能

Key metrics to track

需跟踪的核心指标

  • Time to Interactive (TTI): When page becomes fully interactive
  • Largest Contentful Paint (LCP): When main content is visible
  • First Input Delay (FID): Responsiveness to user interactions
  • Cumulative Layout Shift (CLS): Visual stability
  • Bundle size: Initial JavaScript payload
  • Server response time: TTFB for server-rendered content
  • 交互时间(TTI):页面完全可交互的时间点
  • 最大内容绘制(LCP):主要内容可见的时间点
  • 首次输入延迟(FID):对用户交互的响应速度
  • 累积布局偏移(CLS):视觉稳定性
  • 打包体积:初始JavaScript负载
  • 服务端响应时间:服务端渲染内容的首字节时间(TTFB)

Common pitfalls to avoid

需避免的常见陷阱

Don't:
  • Use barrel imports from large libraries
  • Block parallel operations with sequential awaits
  • Re-render entire trees when only part needs updating
  • Load analytics/tracking in the critical path
  • Mutate arrays with .sort() instead of .toSorted()
  • Create RegExp or heavy objects inside render
Do:
  • Import directly from source files
  • Use Promise.all() for independent operations
  • Memoize expensive components
  • Lazy-load non-critical code
  • Use immutable array methods
  • Hoist static objects outside components
请勿:
  • 从大型库中使用桶式导入
  • 用串行await阻塞并行操作
  • 当仅需更新部分内容时重渲染整个树
  • 在关键路径中加载分析/跟踪代码
  • 使用.sort()修改数组,应使用.toSorted()
  • 在渲染内部创建RegExp或重型对象
请:
  • 直接从源文件导入
  • 对独立操作使用Promise.all()
  • 对昂贵组件进行记忆化
  • 懒加载非关键代码
  • 使用不可变数组方法
  • 将静态对象提升至组件外部

Resources

资源

Version history

版本历史

v0.1.0 (January 2026)
  • Initial release from Vercel Engineering
  • 40+ performance rules across 8 categories
  • Comprehensive code examples and impact analysis
v0.1.0(2026年1月)
  • Vercel Engineering首次发布
  • 8大分类下的40+条性能规则
  • 全面的代码示例和影响分析