Sobes.tech
Middle+

When is it better to use useMemo?

sobes.tech AI

Answer from AI

useMemo is a hook in React used for memoizing computed values to avoid recalculating them on every component render. It is best used when you have a heavy or resource-intensive function whose result depends on certain dependencies, and you want to optimize performance by preventing unnecessary calculations.

Example of usage:

import React, { useMemo } from 'react';

function ExpensiveComponent({ items }) {
  const computedValue = useMemo(() => {
    // Heavy operation, e.g., sorting or filtering a large array
    return items.filter(item => item.active).map(item => item.value).reduce((a, b) => a + b, 0);
  }, [items]);

  return <div>Sum of active values: {computedValue}</div>;
}

Thus, useMemo should be applied when:

  • The calculation result depends on input data (dependencies).
  • The calculation is resource-intensive and may slow down rendering.
  • You want to avoid unnecessary recalculations when data remains unchanged.