R

React Handbook

Clean • Professional

React useMemo Hook – Memoizing Values for Performance

1 minute

React useMemo Hook

In React, functional components re-render whenever their state or props change. Sometimes, components perform expensive calculations on each render, which can hurt performance.

What is useMemo?

useMemo is a React hook that returns a memoized value, recalculating it only when one of its dependencies changes.

Syntax:

const memoizedValue = useMemo(() => {
  // expensive calculation
  return computedValue;
}, [dependencies]);
  • memoizedValue → The cached value
  • [dependencies] → Variables that trigger recalculation when changed

Why Use useMemo?

learn code with durgesh images

  • Optimize expensive calculations: Avoid recalculating the same value on every render.
  • Improve performance: Especially in large component trees or complex computations.
  • Prevent unnecessary re-renders: When used with React.memo for child components.

Example:

import React, { useState, useMemo } from "react";

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

  // Expensive calculation
  const factorial = useMemo(() => {
    console.log("Calculating factorial...");
    const calculateFactorial = n => {
      return n <= 0 ? 1 : n * calculateFactorial(n - 1);
    };
    return calculateFactorial(count);
  }, [count]); // Recalculate only when 'count' changes

  return (
    <div>
      <h1>Factorial of {count}: {factorial}</h1>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <inputtype="text"
        value={text}
        onChange={e => setText(e.target.value)}
        placeholder="Type something..."
      />
    </div>
  );
}

export default App;
  • The factorial is recomputed only when count changes, even if text changes.
  • Without useMemo, factorial would be recalculated every render, which is inefficient for expensive calculations.

useMemo vs useCallback

HookPurposeReturns
useMemoMemoizes values from expensive calculationsMemoized value
useCallbackMemoizes functions to avoid re-creationMemoized function
  • Use useMemo when you want to cache a computed value.
  • Use useCallback when you want to cache a function reference.

Article 0 of 0