Sobes.tech
Middle

Object is passed from parent component to child via props and is stored in useMemo dependency. How many times will useMemo run? How to optimize so that useMemo recalculates only once?

sobes.tech AI

Answer from AI

If an object is passed from a parent component to a child component via props and is used in a useMemo dependency, then useMemo will recalculate every time the parent component renders if the object is recreated on each render (for example, if it is declared directly in JSX or in the function body).

This happens because objects in JavaScript are compared by reference, and each new object creation changes the reference, even if the content is the same.

To ensure useMemo recalculates only once, you need to:

  • Create the object outside the component or memoize it in the parent using useMemo or useCallback so that the reference to the object does not change.

Example:

// In the parent
const memoizedObject = useMemo(() => ({ key: 'value' }), []);

<ChildComponent obj={memoizedObject} />

// In the child component
const memoizedValue = useMemo(() => {
  // calculations with obj
}, [obj]);

This way, useMemo in the child component will only run once because the reference to obj does not change.