React.memo - why is my equality function not being called?

I was having the same issue and the solution was a really dumb one. I'm posting this just in case if someone made the same mistake.

If your memo function does have useState variable make sure that you pass it as a prop. Your memo function also has to be outside of your outer function. So instead of:

function App() {
  const [strVar, setStrVar] = useState("My state str");

  const MyElement = React.memo(() => {
    return (
      <Text>
        {strVar}
      </Text>
    )
  }, (prevProps, nextProps) => {
      console.log("Hello"); //Never called
  });

  return (
    <MyElement/>
  )
}

Do it like this:

const MyElement = React.memo(({strVar}) => {
  return (
    <Text>
      {strVar}
    </Text>
  )
}, (prevProps, nextProps) => {
   console.log("Hello");
});


function App() {
  const [strVar, setStrVar] = useState("My state str");

  return (
    <MyElement strVar = {strVar}/>
  )
}

In short, the reason of this behaviour is due to the way React works.

React expects a unique key for each of the components so it can keep track and know which is which. By using shortid.generate() a new value of the key is created, the reference to the component changes and React thinks that it is a completely new component, which needs rerendering.

In your case, on any change of props in the parent, React will renrender all of the children because the keys are going to be different for all of the children as compared to the previous render.

Please reference this wonderful answer to this topic

Hope this helps!

Tags:

Reactjs