useMemo

useMemo is a React Hook that caches (memoizes) the result of an expensive calculation so it is only recomputed when its dependencies change. It helps avoid redoing costly work on every render.

React

On each render, useMemo checks whether its dependencies changed. If they did, it runs the function again and stores the result; if not, it returns the previously cached value, skipping the work.

Use useMemo for genuinely expensive computations or to keep a stable reference for objects and arrays passed to optimized children. Don't reach for it everywhere — for cheap calculations the overhead isn't worth it.

Syntax

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

Examples

JSX — Recomputes the total only when the numbers array changes; otherwise reuses the cached sum on re-renders.

import { useMemo } from "react";

function Sum({ numbers }) {
  const total = useMemo(() => {
    return numbers.reduce((a, b) => a + b, 0);
  }, [numbers]);
  return <p>Total: {total}</p>;
}

Learn it in a lesson

See also

Back to the Dictionary