Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is useMemo more right way to memoize element in React rather than React.memo?

I was watching youtube video https://www.youtube.com/watch?v=G7RNVYaRS3E (the minute 6:04) and came across the case when the author showed the below code enter image description here and said that wrapping a React component with React.memo does the memoization in a wrong way and suggested to use useMemo for Child component if we really want to memoize the component which made me confused. I tried to use React.memo and it memoized the component accordingly thus I cannot get why the author considers React.memo for a component as incorrect. Can you please explain?

I tried to check if React.memo memoizes the component and it works correctly

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In short: React.memo is a useful tool, but it only works if the props don’t change. The video is pointing out a case where the props change but you might not realize it.


That portion of the video is talking about a specific case, where you pass an element to another component:

const Component = () => {
  const onClick = useCallback(() => {
    // ...
  }, []);
  return (
    <MemoItem onClick={onClick}>
      <MemoChild />
    </MemoChild>
  )
}

<MemoChild /> is being passed into the children prop of MemoItem. The problem with this is that a JSX tag like <MemoChild> /> actually is a shorthand for creating a small object describing what you want to put on the page. That object looks roughly like this:

{
  type: MemoChild,
  props: null
}

Every time Component renders, a brand new object is created describing the memoChild. The object looks very similar, but it’s a new object. MemoItem is using React.memo to skip rendering, but this will only work if its props don’t change. onClick doesn’t change because they’ve wrapped it in useCallback, but children will change on every render and that will break MemoItem’s memoization.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading