1277 Rerender Memo With Default Value 81c47476

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

tools-only Updated 7 repo stars

File contents

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):

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

// Used without optional onClick
<UserAvatar />

Correct (stable default value):

const NOOP = () => {};

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

// Used without optional onClick
<UserAvatar />

tools-only/X-Skills/tree/main/commercial/1277-rerender-memo-with-default-value_81c47476 commit 6357049184

Frequently asked questions

npx skillmds@latest add tools-only/1277-rerender-memo-with-default-value-81c47476