R
Rishtaara
React: The Complete Guide
Lesson 22 of 28Article14 min

useMemo Hook

useMemo runs a function and caches the result until dependencies change. Use it for heavy sorting, filtering, or derived data — not for every variable.

useMemo — cache expensive calculations

useMemo runs a function and caches the result until dependencies change. Use it for heavy sorting, filtering, or derived data — not for every variable.

Real-life example: useMemo is meal prepping on Sunday — you cook once (calculate), eat all week (reuse) until ingredients (deps) change.

Memoized sorted list
import { useMemo, useState } from "react";

function UserTable({ users }) {
  const [sort, setSort] = useState("name");

  const sorted = useMemo(() => {
    return [...users].sort((a, b) => a[sort].localeCompare(b[sort]));
  }, [users, sort]);

  return (
    <ul>
      {sorted.map((u) => (
        <li key={u.id}>{u.name}</li>
      ))}
    </ul>
  );
}

useMemo vs useCallback

useMemo caches a value. useCallback caches a function. useCallback(fn, deps) is roughly useMemo(() => fn, deps).

Real-life example: useMemo stores the cooked dish. useCallback stores the recipe card to cook the same dish again.

  • Profile first with React DevTools
  • React.memo on components + useMemo on props can work together
  • Premature memoization adds complexity without speed gains