It is necessary to memorize a Small/Cheap Component ? - ReactJS

Viewed 58

Lets say i have a child component that just return a div element

Child Component :

function Child() {
  return <div className={styles.alertBox}>No Data Found</div>;
}

it will always re-render when the parent state change, so to prevent it re-render we will wrap it using React.memo

example :

export default function Parent(){
  *some state and setState stuff*

  const MemorizeChild = React.memo(Child)
  return MemorizeChild

By doing that we prevent our Child Component to re-render everytime we change the state

My Question is: did we really need to memorize the Child Component although it just return few line of html and does not execute some heavy function, because we all know that Memorizaition are not Free. in return of Time we trade space (Memory / Cache). if it not can you tell me when should i memorize my component

1 Answers

I would say that it doesn't make much sense to memoize such a component. There is already a similar question, take a look.

It should be used if it's possible to quantify the performance gains from it.

Shortly I suggest using memo when:

  • you know that a component will render quite often
  • component re-renders with the same props
  • component is big enough to have props equality check

Also, you can use profiler to measure how often a React application renders and what the “cost” of rendering is. It can help you identify what parts of an application might need memoization.

Related