Expensive? - useMemo

Understanding <strong>useMemo</strong> in React

The useMemo hook in React is used to optimize performance by memoizing expensive computations. It prevents recalculating values unnecessarily by caching the result of a function when its dependencies don’t change.


Why <strong>useMemo</strong>?

In React, re-rendering components can trigger unnecessary recalculations. useMemo ensures that the computation happens only when needed (i.e., when specified dependencies change).


Custom Hook Example: <strong>useExpensiveCalculation</strong>

Here’s a custom hook that demonstrates using useMemo to optimize an expensive calculation.

Custom Hook Code:

import { useMemo } from "react";

// Custom Hook: Optimizes an expensive computation
const useExpensiveCalculation = (number) => {
  const calculate = (num) => {
    console.log("Running expensive calculation...");
    let result = 0;
    for (let i = 0; i <= 100000000; i++) {
      result += num + i;
    }
    return result;
  };

  const result = useMemo(() => calculate(number), [number]);

  return result;
};

export default useExpensiveCalculation;

How It Works:

  1. <strong>useMemo</strong> Cache:
    • The expensive calculate function runs only if <strong>number</strong> changes.
    • If number remains the same, React uses the cached result.

Usage Example

Here’s a component that uses the custom useExpensiveCalculation hook:

import React, { useState } from "react";
import useExpensiveCalculation from "./useExpensiveCalculation";

const ExpensiveCalculationDemo = () => {
  const [number, setNumber] = useState(1);
  const [increment, setIncrement] = useState(0);

  const result = useExpensiveCalculation(number);

  return (
    <div>
      <h1>useMemo Hook Example</h1>
      <p>Result of Expensive Calculation: {result}</p>

      <button onClick={() => setNumber(number + 1)}>
        Change Input (Number: {number})
      </button>

      {/* Increment unrelated to expensive calculation */}
      <button onClick={() => setIncrement(increment + 1)}>
        Increment Count: {increment}
      </button>
    </div>
  );
};

export default ExpensiveCalculationDemo;

What Happens Here?

  • The expensive calculation (useExpensiveCalculation) only runs when number changes.
  • Clicking "Increment Count" triggers a re-render but does not recalculate the expensive value because numberremains unchanged.

Key Notes About <strong>useMemo</strong>:

  • Syntax: useMemo(() => computation, [dependencies])
  • Only recomputes the value if the dependencies change.
  • Ideal for expensive calculations or derived data.

This example demonstrates how useMemo can optimize performance in functional components, making your React apps more efficient. Let us know if you'd like more details or use cases! 🚀

Slides

Let's take a look at how we can speed up component rendering when performing expensive computations.


The useMemo hook in React is used to optimize performance by memoizing expensive computations. It prevents recalculating values unnecessarily by caching the result of a function when its dependencies don’t change.


Consider the calculateFibonacci function, which uses recursion to compute the Fibonacci sequence. This process is computationally very expensive.


When trying to increment the value of count, the UI is very sluggish as on each re-render, the sequence is recalculated.


The problem occurs on this line executing on each render.


Instead, we can use the useMemo hook, which will cache the result of the computation of the Fibonacci sequence. Similarly to useEffect hook, it has a dependency array that tells the useMemo when it needs to be re-computed.


Try clicking on the Increment Count button to see that the response is much faster! Clicking on Change Input re-calculates the Fibonacci sequence, be patient!