556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / rerender-memo-with-default-value.md
1.1 KB
1--- 2 3title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant 4impact: MEDIUM 5impactDescription: restores memoization by using a constant for default value 6tags: rerender, memo, optimization 7 8--- 9 10## Extract Default Non-primitive Parameter Value from Memoized Component to Constant 11 12When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`. 13 14To address this issue, extract the default value into a constant. 15 16**Incorrect (`onClick` has different values on every rerender):** 17 18```tsx 19const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) { 20 // ... 21}) 22 23// Used without optional onClick 24<UserAvatar /> 25``` 26 27**Correct (stable default value):** 28 29```tsx 30const NOOP = () => {}; 31 32const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) { 33 // ... 34}) 35 36// Used without optional onClick 37<UserAvatar /> 38```