#100DAYSOFCODE Day97

#100DAYSOFCODE Day97

Learn about useMemo

React hooks are amazing. Being able to put all the logic and state management within a function component allows for mind blowing composability.

This power comes with an unfortunate limitation that calculations performed within render will be performed every single render, regardless of whether the inputs for the calculations change, so using useCallback and useMemo can avoid re-render a lot of times.

function Distance({x, y}) {
  const distance = calculateDistance(x, y)
  return (
    <div>
      The distance between {x} and {y} is {distance}.
    </div>
  )
}

If that component’s parent re-renders, or if we add some unrelated state to the component and trigger a re-render, we’ll be calling calculateDistance every render which could lead to a performance bottleneck.

This is why we have the useMemo hook from React:

function Distance({x, y}) {
  const distance = React.useMemo(() => calculateDistance(x, y), [x, y])
  return (
    <div>
      The distance between {x} and {y} is {distance}.
    </div>
  )
}

This allows us to put that calculation behind a function which is only called when the result actually needs to be re-evaluated (when the dependencies change). In the example above the array [x, y] are called “dependencies” and React knows that so long as those do not change, the result of our function will be the same as the last time the function was called.

useMemo (and its sibling useCallback) is nuanced and should not be applied in all cases.

Sources: When to useMemo and useCallback