react-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact & Next.js Performance Patterns
React & Next.js 性能优化模式
Performance optimization guide for React and Next.js applications, based on Vercel Engineering practices. 8 categories organized by impact.
基于Vercel工程实践的React与Next.js应用性能优化指南,按影响程度分为8个类别。
Table of Contents
目录
When to Apply
适用场景
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Optimizing bundle size or load times
- 编写新的React组件或Next.js页面
- 实现数据获取(客户端或服务端)
- 评审代码以排查性能问题
- 优化包体积或加载时间
Quick Reference
快速参考
1. Async Patterns (CRITICAL)
1. 异步模式(CRITICAL)
references/async-patterns.md
- Prevent waterfall chains in API routes -- start promises early, await late
- Defer await until needed -- move await into branches that use it
- Dependency-based parallelization -- with
Promise.all()chaining.then() - Strategic Suspense boundaries -- stream content with
<Suspense>
references/async-patterns.md
- 避免API路由中的请求瀑布链——尽早启动Promise,延迟await操作
- 延迟await到需要时再执行——将await移至使用该结果的分支中
- 基于依赖的并行处理——结合与
Promise.all()链式调用.then() - 合理设置Suspense边界——使用流式传输内容
<Suspense>
2. Bundle Optimization (CRITICAL)
2. 包体积优化(CRITICAL)
references/bundle-optimization.md
- Avoid barrel file imports -- import directly from source files
- Conditional module loading -- load only when feature is activated
- Defer non-critical third-party libraries -- load after hydration
- Dynamic imports for heavy components -- with
next/dynamicssr: false - Preload on user intent -- preload on hover/focus
references/bundle-optimization.md
- 避免桶形文件导入——直接从源文件导入
- 条件式模块加载——仅在功能激活时加载模块
- 延迟加载非关键第三方库——在 hydration 完成后加载
- 对重型组件使用动态导入——搭配使用
ssr: falsenext/dynamic - 根据用户意图预加载——在 hover/focus 时进行预加载
3. Server-Side Performance (HIGH)
3. 服务端性能(HIGH)
references/server-performance.md
- for non-blocking operations -- logging, analytics after response
after() - Authenticate Server Actions -- treat as public endpoints
- Cross-request LRU caching -- share data across sequential requests
- deduplication -- per-request with primitive args
React.cache() - Avoid duplicate RSC serialization -- transform in client, not server
- Parallel fetching via composition -- restructure component tree
- Minimize serialization at boundaries -- pass only needed fields
references/server-performance.md
- 使用处理非阻塞操作——响应完成后执行日志、分析等操作
after() - 对Server Actions进行身份验证——将其视为公开端点
- 跨请求LRU缓存——在连续请求间共享数据
- 去重——针对原始参数按请求去重
React.cache() - 避免重复RSC序列化——在客户端而非服务端进行转换
- 通过组合实现并行获取——重构组件树
- 最小化边界处的序列化——仅传递所需字段
4. Client-Side Patterns (MEDIUM-HIGH)
4. 客户端模式(MEDIUM-HIGH)
references/client-patterns.md
- Deduplicate global event listeners --
useSWRSubscription - Version and minimize localStorage -- schema versioning, try-catch
- Passive event listeners -- for scroll performance
{ passive: true } - SWR for automatic deduplication -- caching and revalidation
references/client-patterns.md
- 全局事件监听器去重——使用
useSWRSubscription - 版本化并最小化localStorage使用——采用 schema 版本控制,搭配try-catch
- 被动事件监听器——为滚动性能设置
{ passive: true } - 使用SWR自动去重——实现缓存与重新验证
5. Re-render Optimization (MEDIUM)
5. 重渲染优化(MEDIUM)
references/rerender-optimization.md
- Defer state reads to usage point -- read in callbacks, not render
- Narrow effect dependencies -- use primitives, not objects
- Derive state during render -- no state + effect for computed values
- Functional setState -- stable callbacks, no stale closures
- Hoist default non-primitive props -- stable defaults for
memo() - Extract to memoized components -- skip computation with early returns
- Interaction logic in event handlers -- not state + effect
- useRef for transient values -- avoid re-render on frequent updates
references/rerender-optimization.md
- 延迟状态读取到使用点——在回调中读取而非渲染阶段
- 缩小effect依赖范围——使用原始值而非对象
- 在渲染阶段派生状态——无需使用state+effect计算值
- 函数式setState——使用稳定回调,避免闭包过时
- 提升非原始默认属性——为提供稳定默认值
memo() - 提取为 memoized 组件——通过提前返回跳过计算
- 交互逻辑放在事件处理程序中——而非state+effect
- 使用useRef存储临时值——避免频繁更新导致重渲染
6. Rendering Performance (MEDIUM)
6. 渲染性能(MEDIUM)
references/rendering-performance.md
- Animate SVG wrapper -- hardware-accelerated CSS on , not
<div><svg> - CSS -- defer off-screen rendering
content-visibility: auto - Hoist static JSX -- extract constants outside components
- Prevent hydration mismatch -- inline script for client-only data
- over manual loading states -- built-in pending state
useTransition
references/rendering-performance.md
- 为SVG容器添加动画——在上使用硬件加速CSS而非直接在
<div>上<svg> - CSS ——延迟渲染屏幕外元素
content-visibility: auto - 提升静态JSX——将常量提取到组件外部
- 避免 hydration 不匹配——使用内联脚本处理客户端独有数据
- 使用替代手动加载状态——利用内置的pending状态
useTransition
7. JavaScript Performance (LOW-MEDIUM)
7. JavaScript性能(LOW-MEDIUM)
references/js-performance.md
- Avoid layout thrashing -- batch DOM reads and writes
- Cache repeated function calls -- module-level Map
- Cache storage API calls -- in-memory cache for localStorage/cookies
- Build index Maps for lookups -- O(1) instead of O(n)
.find() - Loop for min/max -- O(n) instead of O(n log n) sort
references/js-performance.md
- 避免布局抖动——批量处理DOM读取与写入
- 缓存重复函数调用——使用模块级Map
- 缓存存储API调用——为localStorage/cookies提供内存缓存
- 构建索引Map用于查找——用O(1)操作替代O(n)的
.find() - 使用循环查找最大/最小值——用O(n)操作替代O(n log n)的排序
8. Advanced Patterns (LOW)
8. 进阶模式(LOW)
references/advanced-patterns.md
- Store event handlers in refs -- stable effect subscriptions
- Initialize app once per load -- module-level guard
references/advanced-patterns.md
- 将事件处理程序存储在refs中——实现稳定的effect订阅
- 每次加载仅初始化应用一次——使用模块级守卫