react代码如何优化
优化 React 代码的方法
使用 React.memo 和 useMemo/useCallback
React.memo 用于避免不必要的组件重新渲染,适用于纯函数组件。useMemo 缓存计算结果,useCallback 缓存函数引用,减少子组件因父组件更新导致的重复渲染。
const MemoizedComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
const expensiveCalculation = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const handleClick = useCallback(() => doSomething(a, b), [a, b]);
代码分割与懒加载
通过 React.lazy 和 Suspense 实现动态导入,减少初始加载时间。适用于路由级或非关键组件。
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Spinner />}>
<LazyComponent />
</Suspense>
);
}
减少状态提升与合理使用 Context
避免将状态过度提升到高层组件,优先使用局部状态。Context 适合跨层级传递全局数据(如主题、用户信息),但频繁更新的数据可能导致性能问题。
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
虚拟列表优化长列表
使用 react-window 或 react-virtualized 渲染大型列表,仅渲染可视区域内的元素。
import { FixedSizeList as List } from 'react-window';
function MyList({ data }) {
return (
<List height={400} itemCount={data.length} itemSize={50} width={300}>
{({ index, style }) => <div style={style}>{data[index]}</div>}
</List>
);
}
避免内联函数与对象
内联函数和对象会导致子组件每次接收新的 props,触发重新渲染。应将其移至组件外部或使用 useCallback/useMemo。
// 避免
<Button onClick={() => handleClick(id)} />
// 推荐
const handleClick = useCallback((id) => { /* ... */ }, []);
<Button onClick={handleClick} />
使用生产模式构建
确保部署时使用生产环境构建,React 会启用压缩、移除警告等优化。通过 Webpack 配置 mode: 'production' 或设置环境变量 NODE_ENV=production。
性能分析与调试
利用 React DevTools 的 Profiler 组件检测渲染时间,识别不必要的更新。Chrome Performance 工具可分析组件生命周期耗时。
import { unstable_trace as trace } from 'scheduler/tracing';
function MyComponent() {
trace('Render', performance.now(), () => {
// 组件逻辑
});
}
服务端渲染(SSR)与静态生成
对 SEO 或首屏速度要求高的场景,使用 Next.js 等框架实现服务端渲染或静态生成,减少客户端加载压力。

// Next.js 页面示例
export async function getStaticProps() {
return { props: { data: fetchData() } };
}
export default function Page({ data }) {
return <div>{data}</div>;
}






