Lesson

useMemo

10 min reading
Free Course

React useMemo Hook: Memoizing Expensive Derived Values

useMemo caches the computed result of a function between re-renders. During each render, React checks the dependency array; if none of the values changed, React reuses the saved result instead of running a slow sort, filter, or aggregation again.

Caching Expensive Computation and Object References

useMemo solves two distinct problems: skipping heavy CPU work (like filtering 10,000 table rows) and keeping a derived object or array's memory reference stable when passing it to a React.memo child or useEffect.

import { useMemo, useState } from 'react';

export function ProductCatalog({ products }) {
  const [query, setQuery] = useState('');
  const [darkMode, setDarkMode] = useState(false);

  const visibleProducts = useMemo(() => {
    const term = query.trim().toLowerCase();
    return products
      .filter((item) => item.name.toLowerCase().includes(term))
      .sort((a, b) => a.price - b.price);
  }, [products, query]);

  return (
    <section className={darkMode ? 'dark' : 'light'}>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Filter..." />
      <button type="button" onClick={() => setDarkMode((d) => !d)}>Toggle Theme</button>
      <p>Showing {visibleProducts.length} items</p>
    </section>
  );
}

Toggling darkMode re-renders ProductCatalog, yet visibleProducts does not re-filter or re-sort because products and query stayed unchanged.

Common useMemo Mistakes

  • Wrapping Cheap Expressions: Wrapping a + b or formatting a short string in useMemo wastes memory and hurts readability because running the dependency check costs more than the calculation itself.
  • Running Side Effects Inside useMemo: useMemo runs during rendering and must remain pure. Never call state setters, DOM mutations, or fetch inside useMemo.
  • Trusting useMemo as a Permanent Cache: React may discard cached values to free memory in future concurrent features, so only use useMemo as a performance optimization, not for correctness.

Frequently Asked Questions

How do I know if a calculation is slow enough for useMemo?

Measure it with console.time or the React DevTools Profiler. Generally, calculations taking under 1 millisecond do not need manual useMemo.

Can useMemo stabilize a Context Provider's value object?

Yes. Wrapping useMemo(() => ({ user, logout }), [user]) prevents unnecessary re-renders across every consumer whenever the Provider's parent updates.

What happens if the dependency array is empty ([])?

React computes the value once when the component mounts and keeps returning that exact value until the component unmounts.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
React Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum