react如何代码优化
代码拆分与懒加载
使用 React.lazy 和 Suspense 实现组件懒加载,减少初始加载体积。动态导入组件仅在需要时加载,提升页面性能。
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
使用 useMemo 和 useCallback
避免不必要的计算和函数重新创建,通过缓存优化性能。useMemo 用于缓存计算结果,useCallback 用于缓存函数引用。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
减少不必要的重新渲染
通过 React.memo 对组件进行浅比较,避免子组件因父组件无关状态更新而重新渲染。结合 useMemo 和 useCallback 进一步优化。

const MemoizedComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
虚拟列表优化长列表
使用 react-window 或 react-virtualized 实现虚拟滚动,仅渲染可视区域内的列表项,大幅提升长列表性能。
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => <div style={style}>Row {index}</div>;
function App() {
return (
<List height={600} itemCount={1000} itemSize={35} width={300}>
{Row}
</List>
);
}
状态管理优化
避免将全局状态分散在多个组件中,使用集中式状态管理工具(如 Redux、Recoil 或 Context API)并合理划分状态粒度。按需订阅状态,避免全局重新渲染。

const ThemeContext = React.createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<ChildComponent />
</ThemeContext.Provider>
);
}
生产环境构建优化
通过 webpack 或 vite 配置代码压缩、Tree Shaking 和分包策略。移除未使用的代码,压缩资源文件,并启用 React 生产模式。
// webpack.config.js
module.exports = {
mode: 'production',
optimization: {
splitChunks: { chunks: 'all' },
},
};
使用不可变数据
通过 immer 或原生不可变操作(如展开运算符)避免直接修改状态,减少深比较开销并提升可预测性。
const [state, setState] = useState({ items: [] });
setState(prev => ({ ...prev, items: [...prev.items, newItem] }));
性能监控与分析
使用 React DevTools 和 Profiler API 检测性能瓶颈,定位不必要的渲染或高耗时操作。结合 Chrome DevTools 的 Performance 面板分析运行时性能。
function onRenderCallback(
id, phase, actualDuration, baseDuration, startTime, commitTime
) {
console.log(`Component ${id} took ${actualDuration}ms`);
}
<React.Profiler id="App" onRender={onRenderCallback}>
<App />
</React.Profiler>






