Search code examples
reactjsreact-functional-componentreact-memo

React.memo and invalidation in Functional component not invalidating


I have a React functional component wrapped with React.memo as follows

const SpeakerDetail = React.memo(
  ({ record, prop1 }) => {...

When I call this component, I do it like this

const record = {prop1: 'abcd', prop2: 'efgh', prop3: 'ijkl'};
const Speakers = () => {
   ...
   return(
      <SpeakerDetail record={record} prop1={record.prop1}></SpeakerDetail>
   )...

Assuming that my prop1 does indeed change between renders, the above code works as expected meaning that React.memo creates a fresh copy and does not use it's cached version.

The issue is if I don't explicitly pass prop1 as a separate parameter, the React.memo cache version does not recognize that a property of record has changed.

Is there a way to not have to pass in this redundant property to get React.memo to recalculate?

This feels like a deep/shallow copy problem but I'm not sure.


Solution

  • memo HOC

    The memo HOC simply does a shallow reference equality check of the passed props. You can specify an equality function as the second parameter to the memo HOC, that takes the previous and next props that returns true if the comparison would return the same result, false otherwise.

    const SpeakerDetail = React.memo(
      ({ record, prop1 }) => {...},
      (prevProps, nextProps) => {
        if (prevProps.record.prop1 !== nextProps.record.prop1) return false;
        return true;
      },
    );