0

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.

Pete
  • 3,111
  • 6
  • 20
  • 43

1 Answers1

1

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;
  },
);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Hi @DrewReese. For the moment, I've unmarked this question as answered because it seems to not solve my problem. I've created a stackblitz example here as well as posted a new question since the example is now different. https://stackoverflow.com/questions/63123846/react-memo-2nd-parameter-dependency-function-not-working-as-expected Stackblitz URL: https://stackblitz.com/edit/react-upe9vu?file=SpeakerWithMemo.js – Pete Jul 27 '20 at 21:31
  • URL for editing https://stackblitz.com/edit/react-upe9vu – Pete Jul 27 '20 at 21:38
  • 1
    @Pete I've answered that other question. Looks like you were mutating your state object and that was a cause for issue. – Drew Reese Jul 27 '20 at 23:21
  • Side note here. I love the 2nd parameter for comparing prev and next props, but it turns out you don't need to do that if you do proper state management. React seems to figure out the shallow+1 nesting. I updated my stackblitz here to show it: https://stackblitz.com/edit/react-ayfxqg – Pete Jul 28 '20 at 00:34
  • @Pete Yes, that is very likely. I believe it is intended for much more complex prop object shapes/deeper checks. – Drew Reese Jul 28 '20 at 00:48