4

I want to check whether a certain prop changed manually, then use React's built-in comparison function for the other props. E.g.:

React.memo(
  () => <div />,
  (prevProps, nextProps) => {
    if (!nextProps.visible) {
      return true;
    }
    return React.shallowCompare(prevProps, nextProps);
  },
);

I can easily write my own comparison function or copy/paste from React's source, but if React changes their default comparison function then I'd have to manually change my function too. Is there a way to use React's built-in comparison function for React.memo?

Also, AFAIK, react-addons-shallow-compare is outdated.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

1 Answers1

3

Unfortunately, no. React defaults to shallowEqual in the event you don't provide a compare function, but there isn't additional logic for using the default behavior if you return anything special (e.g. return null).

React's usage:

const prevProps = currentChild.memoizedProps;
// Default to shallow comparison
let compare = Component.compare;
compare = compare !== null ? compare : shallowEqual;
if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
...

React isn't currently exporting shallowEqual. However, React's documentation states that it only shallow compares, which is unlikely to change much and can be trivially implemented as you know (example). I'm assuming this decision is to reduce the API their team exposes to developers.

matth
  • 6,112
  • 4
  • 37
  • 43
  • 2
    For reference, React's [`shallowCompare` is here](https://github.com/facebook/react/blob/master/packages/shared/shallowEqual.js); you'll need to copy in their `Object.is` and `Object.prototype.hasOwnProperty`. I've made [a gist](https://gist.github.com/elyobo/934f6896788236670ec4367c89a79412), stripping flow types (and reformatting slightly to my own preferences) if that's easier. – El Yobo Jun 12 '21 at 00:28
  • [This GH issue](https://github.com/facebook/react/issues/16919) (closed) requests that the `shallowCompare` be exported, but it was closed with very little discussion. Please add your thoughts there if you'd find this useful. – El Yobo Jun 12 '21 at 00:29