1.1 KiB
1.1 KiB
title, impact, impactDescription, tags
| title | impact | impactDescription | tags |
|---|---|---|---|
| Extract to Memoized Components | MEDIUM | 支持提前返回 | rerender, memo, useMemo, optimization |
提取为记忆化组件
将耗时工作提取为记忆化组件,以便在计算前支持提前返回。
错误做法(即使在加载时也会计算头像):
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() 进行记忆化。编译器会自动优化重渲染。