react如何优化
减少不必要的重新渲染
使用 React.memo 对函数组件进行记忆化处理,避免在 props 未变化时重新渲染。对于类组件,可以通过继承 PureComponent 或手动实现 shouldComponentUpdate 来优化。
const MyComponent = React.memo(function MyComponent(props) {
/* 渲染逻辑 */
});
合理使用 useMemo 和 useCallback
useMemo 用于缓存计算结果,避免在每次渲染时重复计算。useCallback 用于缓存函数引用,避免因函数引用变化导致子组件不必要的重新渲染。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
虚拟化长列表
对于渲染大量数据的列表,使用虚拟滚动技术(如 react-window 或 react-virtualized)只渲染可视区域内的元素,减少 DOM 节点数量。
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => <div style={style}>Row {index}</div>;
const Example = () => (
<List height={150} itemCount={1000} itemSize={35} width={300}>{Row}</List>
);
代码分割与懒加载
通过动态 import() 语法和 React.lazy 实现组件的懒加载,减少初始加载时的资源体积。结合 Suspense 提供加载状态。
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
优化状态管理
避免将不必要的状态提升到全局(如 Redux),优先使用本地状态。对于复杂状态逻辑,可使用 useReducer 替代多个 useState。
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
default: throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return <button onClick={() => dispatch({ type: 'increment' })}>{state.count}</button>;
}
避免内联函数和对象
内联函数和对象会导致每次渲染时生成新的引用,可能触发子组件不必要的更新。尽量将函数和对象定义在组件外部或通过 useMemo/useCallback 缓存。
// 避免
<Child onClick={() => doSomething()} />
// 推荐
const handleClick = useCallback(() => doSomething(), []);
<Child onClick={handleClick} />
使用生产环境构建
确保生产环境使用压缩后的 React 版本(如通过 Webpack 的 mode: 'production'),这会移除开发环境的警告和调试代码,显著提升性能。
性能监控与分析
使用 React DevTools 的 Profiler 工具分析组件渲染时间和频率。通过 Chrome 的 Performance 面板识别性能瓶颈。
服务端渲染优化
对于 SSR 应用,注意避免同步渲染阻塞主线程,使用 react-helmet 优化 SEO,通过流式渲染(renderToNodeStream)加快首屏显示。







