0

What's the difference between those two patterns ? Is the useMemo usefull ?

Will the number of rerenders change ?

1 - Just rendering a modified prop

const Component = ({ myObject }) => {
  const computedValue = changeMyValueWithSomeCalculus(myObject.value)
  return (
    <div>
       {computedValue}
    </div>
  )
};

2 - Using useMemo

const Component = ({ myObject }) => {
  const computedValue = useMemo(() => {
    return changeMyValueWithSomeCalculus(myObject.value);
  }, [myObject.value]);

  return (
    <div>
       {computedValue}
    </div>
  )
};

I've ran into this SO question very instructive but doesn't help me out with this choice !

Seba99
  • 1,197
  • 14
  • 38
  • Depends on if the called function is time-intensive and how often the dependency changes. – Dave Newton Oct 22 '21 at 12:58
  • In the case number `1` if I have another prop calculated but only the second one updates then both will be calculated again ... And it's not the case in the second pattern right ? – Seba99 Oct 22 '21 at 13:01
  • But what does it change with a time consuming calculus when there's only a unique variable rendered ? – Seba99 Oct 22 '21 at 13:03
  • 1
    useMemo will not change the number of times the component renders. What it changes is the number of times `changeMyValueWithSomeCalculus` gets run. Option 1 runs it on every render. Option 2 runs it only if myObject.value changed. So if that's an expensive function, and myObject.value rarely changes, useMemo can improve performance. – Nicholas Tower Oct 22 '21 at 13:08

0 Answers0