Back to results for “Performance (memo/useMemo)”
React › Hooks

What is the useMemo hook and how does it help with performance?

Intermediate

Answer

useMemo remembers the result of an expensive calculation and only recalculates it when one of its listed dependencies actually changes. This avoids repeating slow work on every single render if the inputs to that calculation have not changed.
function ProductList({ products, searchTerm }) {
  const filteredProducts = useMemo(
    () => products.filter((p) => p.name.includes(searchTerm)),
    [products, searchTerm]
  );
  return <ul>{filteredProducts.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
Real-world example A product list with thousands of items avoids re filtering the entire list on every unrelated re render, since useMemo only recalculates the filtered results when the actual product list or search term changes.

Common follow-ups: Should useMemo be used for every calculation in a component, even simple ones?;What is the difference between useMemo and useCallback?