Files
2026-07-13 21:36:17 +08:00

45 lines
1.1 KiB
Markdown

---
title: Extract to Memoized Components
impact: MEDIUM
impactDescription: 支持提前返回
tags: rerender, memo, useMemo, optimization
---
## 提取为记忆化组件
将耗时工作提取为记忆化组件,以便在计算前支持提前返回。
**错误做法(即使在加载时也会计算头像):**
```tsx
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>
}
```
**正确做法(加载时跳过计算):**
```tsx
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](https://react.dev/learn/react-compiler),则无需手动使用 `memo()``useMemo()` 进行记忆化。编译器会自动优化重渲染。