Ghost

struxadotcloud/struxa

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