react如何缓存组件
React 组件缓存的实现方法
使用 React.memo 进行浅比较缓存
React.memo 是一个高阶组件,用于对函数组件进行浅层 props 比较优化。当组件 props 没有变化时,会直接返回上次渲染结果。
const MemoizedComponent = React.memo(function MyComponent(props) {
/* 使用 props 渲染 */
});
可以自定义比较函数作为第二个参数:
React.memo(MyComponent, (prevProps, nextProps) => {
return prevProps.value === nextProps.value;
});
使用 useMemo 缓存计算结果
useMemo 可以缓存计算密集型操作的返回值,避免每次渲染都重新计算。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
使用 useCallback 缓存回调函数
useCallback 可以缓存回调函数,避免因函数引用变化导致子组件不必要的重新渲染。
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
使用 Context 配合 memo 优化
当使用 Context 时,可以将消费 Context 的部分分离为独立组件并用 memo 包裹:
const ContextConsumer = React.memo(() => {
const value = useContext(MyContext);
return <ExpensiveComponent value={value} />;
});
使用第三方缓存库
对于更复杂的缓存需求,可以考虑以下库:
- react-query:管理服务器状态和缓存
- swr:数据获取和缓存策略
- redux-reselect:创建记忆化的 selector
类组件的 shouldComponentUpdate
对于类组件,可以通过实现 shouldComponentUpdate 来控制更新:
class MyComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// 自定义比较逻辑
return nextProps.value !== this.props.value;
}
}
虚拟化长列表
对于长列表渲染,使用 react-window 或 react-virtualized 只渲染可见部分:
import { FixedSizeList as List } from 'react-window';
<List
height={150}
itemCount={1000}
itemSize={35}
width={300}
>
{Row}
</List>
每种缓存方法都有适用场景,应根据具体需求选择合适方案。过度使用缓存可能导致内存问题或难以追踪的 bug,建议只在性能瓶颈出现时实施优化。







