DEV Community

Cover image for Understanding useMemo in React
Arul .A
Arul .A

Posted on

Understanding useMemo in React

React provides several hooks to improve performance and manage state efficiently. One of these hooks is useMemo, which is used to memoize expensive calculations and avoid unnecessary re-computations during component re-renders.

What is useMemo?

useMemo is a React Hook that stores the result of a calculation and only recalculates it when one of its dependencies changes. This helps improve application performance by preventing expensive operations from running on every render.

Syntax

const memoizedValue = useMemo(() => {
  return expensiveCalculation();
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode
  • The first argument is a function that returns a value.
  • The second argument is a dependency array.
  • React recalculates the value only when a dependency changes.

Why use useMemo?

When a component re-renders, all calculations inside the component are executed again. For simple calculations, this is not a problem. However, for expensive operations such as filtering, sorting, or processing large datasets, repeated calculations can affect performance.

useMemo helps by caching the result and reusing it until the dependencies change.

Example Without useMemo

import React, { useState } from "react";

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

  console.log("Calculating...");
  const square = count * count;

  return (
    <div>
      <h2>Count: {count}</h2>
      <h2>Square: {square}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>

      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, typing in the input field causes the component to re-render, and the calculation runs again even though the count value has not changed.

Example With useMemo

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

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

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <h2>Square: {square}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>

      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now the calculation runs only when the count value changes. Updating the input field will not trigger the calculation again.

Advantages of useMemo

  • Improves performance by avoiding unnecessary calculations.
  • Reduces processing time for expensive operations.
  • Useful when working with large datasets.
  • Helps optimize React applications.

When to Use useMemo

Use useMemo for:

  • Sorting large arrays
  • Filtering large datasets
  • Complex mathematical calculations
  • Creating stable object or array references

Example:

const sortedUsers = useMemo(() => {
  return users.sort((a, b) => a.age - b.age);
}, [users]);
Enter fullscreen mode Exit fullscreen mode

When Not to Use useMemo

Do not use useMemo for simple calculations because it introduces its own overhead.

const total = a + b;
Enter fullscreen mode Exit fullscreen mode

Using useMemo for simple operations often provides no performance benefit.

Top comments (0)