name: rerender-memo description: 使用 React.memo 将昂贵的计算提取到记忆化组件中。当组件执行昂贵的计算,并且当 props 未改变时可以跳过时应用。
提取到记忆化组件
将昂贵的计算提取到记忆化组件中,以便在计算前提前返回。
不正确(即使在加载时也计算头像):
function Profile({ user, loading }: Props) {
const avatar = useMemo(() => {
const id = computeAvatarId(user)
return <Avatar id={id} />
}, [user])
if (loading) return <Skeleton />
return <div>{avatar}</div>
}
正确(在加载时跳过计算):
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatar id={id} />
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />
return (
<div>
<UserAvatar user={user} />
</div>
)
}
注意: 如果你的项目启用了 React Compiler,则不需要手动使用 memo() 和 useMemo() 进行记忆化。编译器会自动优化重新渲染。