DEV Community

Madhavan G
Madhavan G

Posted on

Understanding useMemo in React.

What is useMemo?

useMemo is a React Hook used to store the result of an expensive calculation and only recalculate it when needed.

Syntax:

const memoizedValue = useMemo(() => {
  return calculation();
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

Parameters:

  • Callback Function: Contains the calculation whose result should be cached.
  • Dependencies Array: React recalculates the value only when one of these dependencies changes.

Return Value:
Returns the cached (memoized) value.


Why Do We Use useMemo?

Normally, when a React component re-renders, all the code inside it runs again.

This can become a problem if:

  • The component performs heavy calculations.
  • Large lists need filtering or sorting.
  • Expensive operations run repeatedly.

useMemo helps by:

✅ Improving performance

✅ Reducing unnecessary calculations

✅ Making applications more efficient


Without useMemo:

function App() {
  const [count, setCount] = useState(0);

  const expensiveCalculation = () => {
    console.log("Calculating...");
    return 1000000 * 1000000;
  };

  const result = expensiveCalculation();

  return (
    <div>
      <h2>Result: {result}</h2>
      <button onClick={() => setCount(count + 1)}>
        Count: {count}
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Problem

Whenever the button is clicked:

  • State changes.
  • Component re-renders.
  • expensiveCalculation() runs again.
  • Performance may decrease.

Using useMemo:


import { useState, useMemo } from "react";

function App() {
  const [count, setCount] = useState(0);

  const result = useMemo(() => {
    console.log("Calculating...");
    return 1000000 * 1000000;
  }, []);

  return (
    <div>
      <h2>Result: {result}</h2>
      <button onClick={() => setCount(count + 1)}>
        Count: {count}
      </button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

What Happens?

  • Component renders for the first time.
  • useMemo calculates the value.
  • Value is stored in memory.
  • Clicking the button causes a re-render.
  • React reuses the stored value.
  • Calculation does not run again.

Top comments (0)