Do we need React.memo in all of the components? #9
Replies: 1 comment 3 replies
-
Hello there, Generally I have my own guideline and sort of a checklist for "When to use
However, before I wrote this replay I did some further investigations on the matter and reviewed our components. I did figure it out that using Let me explain it through a few examples: const Button = React.memo(({ onClick }) => <button onClick={onClick}>...</button>); const App = () => {
return <Button onClick={(e) => console.log(e)} />
}; Every time a parent component defines a callback for its child, it creates new function instances and since a new function instance has a different reference, the memoization of The same things happen when the child component accepts an object or even the I know for a fact that comparing the tree returned by the component most of the time is more expensive than comparing a pair of props through an equality check; However, if user breaks the memoization then you gain no performance benefits but also run for naught the comparison function. So to wrap this up, I'm going to remove import Button from "@sonnat/ui/Button";
const MemoizedButton = React.memo(Button) as typeof Button;
const App = () => {
const handleOnClick = React.useCallback((event: MouseEvent) => {
console.log(event);
}, []);
return <MemoizedButton onClick={handleOnClick} />;
}; Thanks again for your review, it helped a lot and we are going to have a better performance (Both speed-wise and memory-wise) because of this discussion. |
Beta Was this translation helpful? Give feedback.
-
Hello,
As I reviewed and read this repo, It raised a question for me.
I'm not sure about this, but I would like to know your reasons for using React.memo in almost all components.
As I know about React.memo, it has a shallow comparison and it is mostly used in those kinds of components that have expensive calculations. Here you used that in a simple component like Portal. Maybe you thought so the children of Portal component has an expensive calculation, But I should say that the components that are passed to this component as a child can be memorized. I think this is not a proper use of React.memo. It's semantically problematic and arguably costs you more in terms of memory allocation and performance.
Now, as far as I knew, and based on the explanations I gave, I wanted to know your point of view on this issue, and I would be very happy to hear your opinion. Thank you.
Beta Was this translation helpful? Give feedback.
All reactions