React hooks——memo
一、简介
React.memo
是 React 提供的一个高阶组件(Higher-Order Component),用于优化函数组件的渲染性能,它通过浅比较(shallow compare)props 的变化来决定是否重新渲染组件。
1.1 基本用法
const MyComponent = React.memo((props) => {/* 使用 props 渲染 */
});
1.2 主要特点
性能优化:仅在 props 发生变化时重新渲染组件
浅比较:默认使用浅比较(shallow comparison)来比较新旧 props
自定义比较:可以传入第二个参数来自定义比较逻辑
1.3 自定义比较函数
const MyComponent = React.memo((props) => {/* 使用 props 渲染 */},(prevProps, nextProps) => {/* 返回 true 表示跳过渲染,false 表示需要渲染 */return prevProps.value === nextProps.value;}
);
1.4 使用场景
纯展示组件(Pure Presentational Components)
渲染成本较高的组件
频繁重新渲染但 props 变化不大的组件
二、代码实现
import { memo, useState } from "react";// 子组件
const ChildComponent = memo(({ name }) => {console.log("子组件重新渲染了");return (<div><h1>子组件name: {name}</h1></div>);
});export default function App() {const [count, setCount] = useState(0);const [name, setName] = useState("c-n");console.log("父组件重新渲染了");return (<div><button onClick={() => setCount(count + 1)}>+1</button><ChildComponent name={name} /></div>);
}