AgentSkillsCN

extract-default-non-primitive-parameter-to-constant

从已记忆的组件中,将默认的非原始参数值提取为常量

SKILL.md
--- frontmatter
name: extract-default-non-primitive-parameter-to-constant
description: Extract Default Non-primitive Parameter Value from Memoized Component to Constant

Extract Default Non-primitive Parameter Value from Memoized Component to Constant

When 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().

To address this issue, extract the default value into a constant.

Incorrect (onClick has different values on every rerender):

tsx
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
  // ...
})

// Used without optional onClick
<UserAvatar />

Correct (stable default value):

tsx
const NOOP = () => {};

const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
  // ...
})

// Used without optional onClick
<UserAvatar />