Skip to content

Understanding the useMemo Hook in React

In this article, we will learn how to use the useMemo hook in React.

What is the useMemo Hook?

The useMemo hook is used to memoize the result of a function so that it is only recomputed when its dependencies change. It is similar to the React.memo higher-order component, but it works at the hook level.

The useMemo hook takes two arguments:

The value returned by the function is memoized until one of the dependencies changes.

Basic template of the useMemo hook

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

When to Use the useMemo Hook?

Example

Let’s see an example of how to use the useMemo hook to memoize the result of an expensive calculation.

import React, { useMemo } from "react";

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

  const factorial = useMemo(() => {
    console.log("Calculating factorial...");
    let result = 1;
    for (let i = 1; i <= count; i++) {
      result *= i;
    }
    return result;
  }, [count]);

  return (
    <div>
      <h1>Factorial of {count} is {factorial}</h1>
      <button onClick={() => setCount(count + 1)}>Calculate Factorial</button>
    </div>
  );
}

export default App;

In this example, we have a component that calculates the factorial of a number. The factorial value is memoized using the useMemo hook with the count as a dependency. The factorial value is only re-computed when the count changes.