react-performance-optimization
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Performance Optimization
React性能优化
Expert guidance for optimizing React application performance through memoization, code splitting, virtualization, and efficient rendering strategies.
通过记忆化、代码分割、虚拟化和高效渲染策略优化React应用性能的专业指南。
When to Use This Skill
何时使用该技能
- Optimizing slow-rendering React components
- Reducing bundle size for faster initial load times
- Improving responsiveness for large lists or data tables
- Preventing unnecessary re-renders in complex component trees
- Optimizing state management to reduce render cascades
- Improving perceived performance with code splitting
- Debugging performance issues with React DevTools Profiler
- 优化渲染缓慢的React组件
- 减小包体积以加快初始加载速度
- 提升大型列表或数据表的响应速度
- 避免复杂组件树中的不必要重渲染
- 优化状态管理以减少渲染级联
- 通过代码分割提升感知性能
- 使用React DevTools Profiler调试性能问题
Core Concepts
核心概念
React Rendering Optimization
React渲染优化
React re-renders components when props or state change. Unnecessary re-renders waste CPU cycles and degrade user experience. Key optimization techniques:
- Memoization: Cache component renders and computed values
- Code splitting: Load code on demand for faster initial loads
- Virtualization: Render only visible list items
- State optimization: Structure state to minimize render cascades
当props或state发生变化时,React会重新渲染组件。不必要的重渲染会浪费CPU资源并降低用户体验。关键优化技术:
- 记忆化(Memoization):缓存组件渲染结果和计算值
- 代码分割:按需加载代码以加快初始加载
- 虚拟化:仅渲染可见的列表项
- 状态优化:结构化状态以最小化渲染级联
When to Optimize
何时进行优化
- Profile first: Use React DevTools Profiler to identify actual bottlenecks
- Measure impact: Verify optimization improves performance
- Avoid premature optimization: Don't optimize fast components
- 先分析:使用React DevTools Profiler识别实际性能瓶颈
- 衡量影响:验证优化是否真的提升了性能
- 避免过早优化:不要对运行快速的组件进行优化
Quick Reference
快速参考
Load detailed patterns and examples as needed:
| Topic | Reference File |
|---|---|
| React.memo, useMemo, useCallback patterns | |
| Code splitting with lazy/Suspense, bundle optimization | |
| Virtualization for large lists (react-window) | |
| State management strategies, context splitting | |
| useTransition, useDeferredValue (React 18+) | |
| React DevTools Profiler, performance monitoring | |
| Common pitfalls and anti-patterns | |
根据需要加载详细的模式和示例:
| 主题 | 参考文件 |
|---|---|
| React.memo、useMemo、useCallback 模式 | |
| 使用lazy/Suspense进行代码分割、包优化 | |
| 大型列表虚拟化(react-window) | |
| 状态管理策略、上下文拆分 | |
| useTransition、useDeferredValue(React 18+) | |
| React DevTools Profiler、性能监控 | |
| 常见陷阱与反模式 | |
Optimization Workflow
优化工作流
1. Identify Bottlenecks
1. 识别瓶颈
bash
undefinedbash
undefinedOpen React DevTools Profiler
打开React DevTools Profiler
Record interaction → Analyze flame graph → Find slow components
记录交互 → 分析火焰图 → 找到缓慢的组件
**Look for:**
- Components with yellow/red bars (slow renders)
- Unnecessary renders (same props/state)
- Expensive computations on every render
**重点关注:**
- 带有黄/红色条的组件(渲染缓慢)
- 不必要的渲染(props/state未变化)
- 每次渲染时的昂贵计算2. Apply Targeted Optimizations
2. 应用针对性优化
For unnecessary re-renders:
- Wrap component with
React.memo - Use for stable function references
useCallback - Check for inline objects/arrays in props
For expensive computations:
- Use to cache results
useMemo - Move calculations outside render when possible
For large lists:
- Implement virtualization with react-window
- Ensure proper unique keys (not index)
For slow initial load:
- Add code splitting with
React.lazy - Analyze bundle size with webpack-bundle-analyzer
- Use dynamic imports for heavy dependencies
针对不必要的重渲染:
- 使用包裹组件
React.memo - 使用获取稳定的函数引用
useCallback - 检查props中的内联对象/数组
针对昂贵计算:
- 使用缓存计算结果
useMemo - 尽可能将计算移到渲染外部
针对大型列表:
- 使用react-window实现虚拟化
- 确保使用正确的唯一key(不要用索引)
针对初始加载缓慢:
- 使用添加代码分割
React.lazy - 使用webpack-bundle-analyzer分析包体积
- 对重型依赖使用动态导入
3. Verify Improvements
3. 验证优化效果
bash
undefinedbash
undefinedRecord new Profiler session
记录新的Profiler会话
Compare before/after metrics
对比优化前后的指标
Ensure optimization actually helped
确保优化确实起到了作用
undefinedundefinedCommon Patterns
常见模式
Memoize Expensive Components
记忆化昂贵组件
jsx
import { memo } from 'react';
const ExpensiveList = memo(({ items, onItemClick }) => {
return items.map(item => (
<Item key={item.id} data={item} onClick={onItemClick} />
));
});jsx
import { memo } from 'react';
const ExpensiveList = memo(({ items, onItemClick }) => {
return items.map(item => (
<Item key={item.id} data={item} onClick={onItemClick} />
));
});Cache Computed Values
缓存计算值
jsx
import { useMemo } from 'react';
function DataTable({ items, filters }) {
const filteredItems = useMemo(() => {
return items.filter(item => filters.includes(item.category));
}, [items, filters]);
return <Table data={filteredItems} />;
}jsx
import { useMemo } from 'react';
function DataTable({ items, filters }) {
const filteredItems = useMemo(() => {
return items.filter(item => filters.includes(item.category));
}, [items, filters]);
return <Table data={filteredItems} />;
}Stable Function References
稳定函数引用
jsx
import { useCallback } from 'react';
function Parent() {
const handleClick = useCallback((id) => {
console.log('Clicked:', id);
}, []);
return <MemoizedChild onClick={handleClick} />;
}jsx
import { useCallback } from 'react';
function Parent() {
const handleClick = useCallback((id) => {
console.log('Clicked:', id);
}, []);
return <MemoizedChild onClick={handleClick} />;
}Code Split Routes
路由代码分割
jsx
import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
const Reports = lazy(() => import('./Reports'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/reports" element={<Reports />} />
</Routes>
</Suspense>
);
}jsx
import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
const Reports = lazy(() => import('./Reports'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/reports" element={<Reports />} />
</Routes>
</Suspense>
);
}Virtualize Large Lists
大型列表虚拟化
jsx
import { FixedSizeList } from 'react-window';
function VirtualList({ items }) {
return (
<FixedSizeList
height={600}
itemCount={items.length}
itemSize={80}
width="100%"
>
{({ index, style }) => (
<div style={style}>{items[index].name}</div>
)}
</FixedSizeList>
);
}jsx
import { FixedSizeList } from 'react-window';
function VirtualList({ items }) {
return (
<FixedSizeList
height={600}
itemCount={items.length}
itemSize={80}
width="100%"
>
{({ index, style }) => (
<div style={style}>{items[index].name}</div>
)}
</FixedSizeList>
);
}Common Mistakes
常见错误
- Over-memoization: Don't memoize simple, fast components (adds overhead)
- Inline objects/arrays: New references break memoization ()
config={{ theme: 'dark' }} - Missing dependencies: Stale closures in useCallback/useMemo
- Index as key: Breaks reconciliation when list order changes
- Single large context: Causes widespread re-renders on any update
- No profiling: Optimizing without measuring wastes time
- 过度记忆化:不要对简单、快速的组件进行记忆化(会增加开销)
- 内联对象/数组:新的引用会破坏记忆化(例如)
config={{ theme: 'dark' }} - 缺少依赖项:useCallback/useMemo中的过时闭包
- 使用索引作为key:当列表顺序变化时会破坏协调过程
- 单一大型上下文:任何更新都会导致广泛的重渲染
- 未进行分析:没有衡量就进行优化只是浪费时间
Performance Checklist
性能检查清单
Before optimizing:
- Profile with React DevTools to identify bottlenecks
- Measure baseline performance metrics
Optimization targets:
- Memoize expensive components with stable props
- Cache computed values with useMemo (if actually expensive)
- Use useCallback for functions passed to memoized children
- Implement code splitting for routes and heavy components
- Virtualize lists with >100 items
- Provide stable keys for list items (unique IDs, not index)
- Split state by update frequency
- Use concurrent features (useTransition, useDeferredValue) for responsiveness
After optimizing:
- Profile again to verify improvements
- Check bundle size reduction (if applicable)
- Ensure no regressions in functionality
优化前:
- 使用React DevTools分析以识别瓶颈
- 衡量基准性能指标
优化目标:
- 对带有稳定props的昂贵组件进行记忆化
- 使用useMemo缓存计算值(如果确实昂贵)
- 对传递给记忆化子组件的函数使用useCallback
- 为路由和重型组件实现代码分割
- 对超过100项的列表进行虚拟化
- 为列表项提供稳定的key(唯一ID,而非索引)
- 按更新频率拆分状态
- 使用并发特性(useTransition、useDeferredValue)提升响应速度
优化后:
- 再次分析以验证优化效果
- 检查包体积是否减小(如适用)
- 确保功能没有回归
Resources
资源
- React Docs - Performance: https://react.dev/learn/render-and-commit
- React DevTools: Browser extension for profiling
- react-window: https://github.com/bvaughn/react-window
- Bundle analyzers: webpack-bundle-analyzer, rollup-plugin-visualizer
- Lighthouse: Chrome DevTools performance audit
- React文档 - 性能:https://react.dev/learn/render-and-commit
- React DevTools:用于性能分析的浏览器扩展
- react-window:https://github.com/bvaughn/react-window
- 包分析工具:webpack-bundle-analyzer、rollup-plugin-visualizer
- Lighthouse:Chrome DevTools性能审计工具