What is useMemo?

useMemo is a React hook that memoizes the result of a function to avoid unnecessary recalculations.

It helps optimize performance by recomputing a value only when one of its dependencies has changed.

const result = useMemo(() => someExpensiveFunction(a, b), [a, b]);

// If you pass an empty array ([]) as the dependency list to useMemo,
// the memoized value will only be calculated once, on the initial render
const memoizedValue = useMemo(() => expensiveCalculation(), []);


You should use useMemo when:

  1. The computation is expensive and can affect performance.
  2. The result of the computation is passed down as a prop to child components and you want to avoid unnecessary re-renders (Child component is wrapped in React.memo).

You should avoid useMemo if:

  • The computation is not expensive and the performance benefit is minimal.
  • The memoization itself might add more overhead (due to the comparison of dependencies, memoized storage) than the recomputation.
  • The dependencies of the memoized value are trivial or unlikely to change.