Reputation: 191
Ok, React.memo HOC mimics for a "function component" what extending React.PureComponent would do for a "class component".
If some rerendering was triggered by some parent component, pure components don’t rerender if its props haven’t changed. Ok
But i can’t understand when i should not use React.memo for function components. In my mind, it appears to be always the best solution, in a way that should be the default behavior of React components. But it isn’t. What am i not understanding of this? In which example we should not use React.memo or rely on pure components?
And if my React Component shouldn't be Pure but I made it so, what are the disadvantages?
Upvotes: 1
Views: 1262
Reputation: 5235
But i can’t understand when i should not use React.memo for function components.
First, let's understand when and why we should use React.memo
and then we'll see when not to use it.
The usecase of React.memo
comes in case you'd not want to re-render the component when the props haven't changed. So by default, referential integrity check is performed to check if a prop is changed. Now if there's a primitive type this check can be easily be performed. But if the props is function
or object
this comparison is not so straightforward.
For e.g
var fun = () => {};
var anotherFun = ()=>{};
console.log(fun === anotherFun); //returns false
So when props is a function or object, if you try to compare with the previous value of it, it will return false and re-rendering will be done if you solely rely on this comparison
So this is why you almost always see React.memo
is accompanied by useCallBack
in the parent function that's passing the props. This is to check the referential integrity. useCallBack
ensures that the new Prop hasn't changed and inside the child component React.memo
compares with its previous value (through shallow comparison) and in case this is unchanged, it avoids re-rendering.
So why shouldn't this be default behavior in React?
That's because this comparison come with a cost. In the background these comparisons and the computation has to happen which can be expensive if the gain is not proportionate.
Imagine if you use useCallBack for a method that's not too expensive in nature and also use React.memo inside the child component that takes it as a parameter. For every cycle of rendering in the parent component these computations will be performed which might slow down the performance instead of actually improving it.
Upvotes: 1