返回 AiToEarn
rerender-memo.md
1 ---
2 title: Extract to Memoized Components
3 impact: MEDIUM
4 impactDescription: enables early returns
5 tags: rerender, memo, useMemo, optimization
6 ---
7
8 ## Extract to Memoized Components
9
10 Extract expensive work into memoized components to enable early returns before computation.
11
12 **Incorrect (computes avatar even when loading):**
13
14 ```tsx
15 function Profile({ user, loading }: Props) {
16 const avatar = useMemo(() => {
17 const id = computeAvatarId(user)
18 return <Avatar id={id} />
19 }, [user])
20
21 if (loading) return <Skeleton />
22 return <div>{avatar}</div>
23 }
24 ```
25
26 **Correct (skips computation when loading):**
27
28 ```tsx
29 const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
30 const id = useMemo(() => computeAvatarId(user), [user])
31 return <Avatar id={id} />
32 })
33
34 function Profile({ user, loading }: Props) {
35 if (loading) return <Skeleton />
36 return (
37 <div>
38 <UserAvatar user={user} />
39 </div>
40 )
41 }
42 ```
43
44 **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
45
45 lines MARKDOWN