_react如何做性能优化
使用React.memo和useMemo优化组件渲染
React.memo用于缓存函数组件,避免不必要的重新渲染。只有当props发生变化时才会重新渲染。对于复杂计算,使用useMemo缓存计算结果,避免重复计算。
const MemoizedComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
const expensiveCalculation = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
避免内联函数和对象
内联函数和对象会导致每次渲染时生成新的引用,触发子组件不必要的更新。将函数或对象提升到组件外部或使用useCallback和useMemo缓存。
const handleClick = useCallback(() => {
console.log('Clicked');
}, []);
const config = useMemo(() => ({ color: 'red' }), []);
虚拟化长列表
对于渲染大量数据的列表,使用虚拟滚动技术(如react-window或react-virtualized)仅渲染可见区域的内容,减少DOM节点数量。
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const VirtualizedList = () => (
<List height={300} itemCount={1000} itemSize={35} width={300}>
{Row}
</List>
);
使用生产模式构建
开发模式下React包含额外的警告和检查,性能较差。确保生产环境使用生产模式构建,通过移除开发工具和优化代码提升性能。
npm run build
代码分割与懒加载
通过React.lazy和Suspense实现组件懒加载,减少初始加载时间。结合Webpack的动态导入功能拆分代码块。
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
优化状态管理
避免将不必要的状态放在全局存储中。局部状态优先使用useState或useReducer。对于频繁更新的状态,考虑使用不可变数据库(如Immer)减少渲染开销。
使用Profiler分析性能
React DevTools的Profiler工具可识别渲染慢的组件。通过分析火焰图和提交记录,定位性能瓶颈并针对性优化。
import { Profiler } from 'react';
function onRenderCallback(
id,
phase,
actualDuration,
baseDuration,
startTime,
commitTime
) {
console.log(`Component ${id} took ${actualDuration}ms`);
}
<Profiler id="MyComponent" onRender={onRenderCallback}>
<MyComponent />
</Profiler>
减少不必要的上下文更新
Context的value变化会导致所有消费者重新渲染。拆分Context或使用memo优化子组件,避免全局状态变动触发大面积更新。
使用Web Workers处理密集型任务
将CPU密集型任务(如数据处理)移至Web Worker,避免阻塞主线程导致UI卡顿。
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => setResult(e.data);





