SmartCodingTips

🧠 useMemo() in React

useMemo() is a performance optimization hook in React. It memorizes the result of a computation so it only re-runs when its dependencies change.


⚡ 1. Why useMemo?

Avoid re-running expensive calculations on every render by memoizing the result:


import { useMemo, useState } from 'react';

function ExpensiveComponent({ num }) {
  const result = useMemo(() => {
    console.log('Calculating...');
    let total = 0;
    for (let i = 0; i < 100000000; i++) {
      total += i;
    }
    return total * num;
  }, [num]);

  return <p>Calculated Value: {result}</p>;
}

🔗 2. Syntax


const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

🧩 3. When to Use

  • Heavy or expensive computations
  • Deriving values from props or state
  • Preventing unnecessary re-renders

🚫 4. Don't Overuse It

Only use useMemo() when there's a real performance bottleneck. Otherwise, it adds unnecessary complexity.

Remember: useMemo() caches a value — not a function. For memoizing functions, use useCallback().