Open In App

ReactJS useMemo Hook

Last Updated : 08 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The useMemo Hook is a built-in React Hook that helps optimize performance by memoizing the result of a computation and reusing it unless its dependencies change. This prevents expensive computations from being re-executed unnecessarily during component re-renders.

Syntax

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • The first argument is a function that returns the computed value.
  • The second argument is an array of dependencies. When any of these dependencies change, the function gets re-evaluated.

Let’s now see some of the Practical Applications of useMemo

1. Optimizing Expensive Calculations

Let’s take an example where we have an expensive computation that should not be recalculated on every render.

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

function App() {
    const [number, setNumber] = useState(0);
    const squaredNum = useMemo(() => squareNum(number), [number]);
    const [counter, setCounter] = useState(0);
    const onChangeHandler = (e) => {
        setNumber(e.target.value);
    };
    const counterHander = () => {
        setCounter(counter + 1);
    };
    return (
        <div className="App">
            <h1>Welcome to Geeksforgeeks</h1>
            <input
                type="number"
                placeholder="Enter a number"
                value={number}
                onChange={onChangeHandler}
            ></input>

            <div>OUTPUT: {squaredNum}</div>
            <button onClick={counterHander}>Counter ++</button>
            <div>Counter : {counter}</div>
        </div>
    );
}
function squareNum(number) {
    console.log("Squaring will be done!");
    return Math.pow(number, 2);
}
export default App;

Output

UseMemo2

In this example

  • useState manages number (user input) and counter (button clicks).
  • useMemo caches squareNum(number), recalculating only when number changes.
  • The input field updates the number state when changed.
  • Clicking “Counter ++” increases the counter state.
  • The component displays the input, memoized squared value, and counter.

2. Preventing Unnecessary Re-renders

Sometimes, passing objects or arrays as props to child components can trigger unnecessary re-renders due to reference changes. useMemo can help stabilize such values.

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

function Child({ userInfo }) {
    console.log("Child component rendered");
    return <p>User: {userInfo.name}</p>;
}
function Parent() {
    const [count, setCount] = useState(0);
    const userInfo = useMemo(() => ({ name: "GeeksforGeeks" }), []);
    return (
        <div>
            <p>Count: {count}</p>
            <Child userInfo={userInfo} />
            <button onClick={() => setCount(count + 1)}>Increment Count</button>
        </div>
    );
}
export default Parent;

Output

UseMemo

In this example

  • React, useState, and useMemo are imported for state management and optimization.
  • ChildComponent displays userInfo.name and logs renders.
  • ParentComponent memoizes userInfo to prevent re-creation.
  • Clicking the button updates count, re-rendering ParentComponent.
  • ParentComponent displays count, ChildComponent, and the button.

When to Use useMemo?

You should use useMemo when

  • You have expensive calculations that do not need to be re-executed unless certain dependencies change.
  • You are dealing with large data sets and need to optimize performance.
  • You want to prevent unnecessary re-renders of child components by ensuring stable references.

However, avoid overusing useMemo as it can add complexity and memory overhead. Use it only when necessary.

Performance Optimization Using useMemo

Using useMemo correctly can significantly enhance the performance of React applications. However, improper usage may lead to unnecessary memory usage and increased complexity. Here are some key considerations:

  • Avoid using useMemo for trivial calculations: If the computation is lightweight, memoization may introduce unnecessary complexity.
  • Use it for expensive calculations: Tasks such as filtering large datasets or performing intensive calculations can benefit from useMemo.
  • Stabilize object and array references: When passing objects or arrays to child components, useMemo helps maintain the same reference and prevents unnecessary re-renders.
  • Measure before optimizing: Always analyze your app’s performance using React DevTools or profiling tools before introducing useMemo.

Key Takeaways

  • Performance optimization: useMemo helps optimize expensive calculations.
  • Prevents unnecessary re-renders: Helps in stabilizing reference values passed as props.
  • Use it wisely: Overuse of useMemo can lead to unnecessary complexity.


Similar Reads

three90RightbarBannerImg