Home > Software engineering >  on component re rendering in react does the objects defined inside the component also created new as
on component re rendering in react does the objects defined inside the component also created new as

Time:01-26

on component re rendering in react does the objects defined inside the component also created new as functions do , if yes then if we are passing it as props then the particular child component would also be called , so it is wise to use useMemo hook , for example const selected = useMemo(() => selectedColumn, [selectedColumn]);

I am confused for the same

CodePudding user response:

It depends on what kind of value it is. Some kinds of value will always give you a new reference when the code is run again (objects, arrays, functions, etc.), while others will always give you the same reference (booleans, numbers, strings, etc.)

{} === {}               // false
[] === []               // false
(() => 3) === (() => 3) // false

false === false         // true
42 === 42               // true
"hello" === "hello"     // true

In the first case you should use useMemo, or useCallback for functions, or just avoid passing such values to the children if possible.

In the second case there is no point in using useCallback at all, because the new value is already equal to the old value.

Edit: To clarify a bit more, when a component rerenders then all of its children, grandchildren, etc. rerender as well. This has nothing to do with props or useMemo. You can prevent it by using React.memo or by moving your state down to avoid rerendering components high up in the tree. See also https://overreacted.io/before-you-memo/

CodePudding user response:

Yes. When a component re-renders, any objects or variables inside the components will be recreated, and will cause the child component to re-render if these objects/variables were passed as props.

Using useMemo hook will let you "memoize" the object/variable and it will prevent unnecessary re-renders.

In the example you have given above, child component will not rerender unless selectedColumn has changed.

Please read docs below for more details. https://beta.reactjs.org/reference/react/useMemo#skipping-re-rendering-of-components

  • Related