useMemo Hook in React – Complete Guide with Examples

Introduction

React provides several built-in hooks to optimize performance, and one of the most useful among them is the useMemo Hook.

What is useMemo in React?

The useMemo Hook is used to memoize (cache) the result of a computation so that React does not need to re-calculate it on every render.

In simple words:

useMemo remembers the result of a function and only recalculates it when its dependencies change.

This helps improve performance by avoiding unnecessary expensive calculations.

Syntax of useMemo


const memoizedValue = useMemo(() => {
 // expensive calculation
 return result;
}, [dependencies]);

Parameters:

  1. Function (callback) – The computation you want to memoize.
  2. Dependency array – React will recompute the value only when these values change.

Why use useMemo?

In React, every time a component re-renders:

  • All functions run again
  • All calculations are executed again

If a calculation is heavy (like filtering a large list, mathematical operations, or data processing), it can slow down your app.

useMemo solves this problem by

  • Storing previous computation results
  • Reusing them if dependencies have not changed
  • Improving performance

Simple Example of useMemo

Let’s understand with a basic example:


import React, { useMemo, useState } from "react";
function App() {
 const [count, setCount] = useState(0);
 const [number, setNumber] = useState(10);
 const expensiveCalculation = (num) => {
   console.log("Calculating...");
   return num * 2;
 };
 const result = useMemo(() => {
   return expensiveCalculation(number);
 }, [number]);
 return (
   <div>
     <h1>Result: {result}</h1>
     <button onClick={() => setCount(count + 1)}>
       Increase Count ({count})
     </button>
     <button onClick={() => setNumber(number + 1)}>
       Change Number
     </button>
   </div>
 );
}
export default App;

How this works?

  • When the count changes → component re-renders
  • But useMemo does NOT recalculate expensiveCalculation
  • It only recalculates when number changes

So:

 ✔ Faster performance
✔ No unnecessary computation

useMemo vs Normal Function

Feature Normal Function useMemo
Re-calculation Every render Only when dependencies change
Performance Slower in heavy operations Optimized
Memory usage Low Slightly higher (stores cached value)

When should you use useMemo?

You should use useMemo only when:

1. Expensive calculations

Example:

  • Sorting large arrays
  • Filtering large datasets
  • Complex mathematical operations

2. Prevent unnecessary re-calculation

If a value is not changing frequently but calculation is heavy.

3. Optimizing list rendering

When working with large lists or tables.

Real-World Example: Filtering List


import React, { useMemo, useState } from "react";
const usersList = [
 "Amit",
 "Rahul",
 "Suresh",
 "Ankit",
 "Ravi",
 "Neha",
 "Priya"
];
function App() {
 const [search, setSearch] = useState("");
 const filteredUsers = useMemo(() => {
   console.log("Filtering users...");
   return usersList.filter(user =>
     user.toLowerCase().includes(search.toLowerCase())
   );
 }, [search]);
 return (
   <div>
     <input
       type="text"
       placeholder="Search user..."
       value={search}
       onChange={(e) => setSearch(e.target.value)}
     />
     <ul>
       {filteredUsers.map((user, index) => (
         <li key={index}>{user}</li>
       ))}
     </ul>
   </div>
 );
}
export default App;

What happens here?

  • Filtering runs only when search changes
  • Not on every render
  • Improves performance in large datasets

Common Mistakes with useMemo

❌ 1. Using useMemo everywhere

Not every value needs memoization. It can even reduce performance if overused.

❌ 2. Ignoring dependency array

If dependencies are missing, it can give stale or incorrect values

❌ 3. Using it for simple operations

Example:


const value = useMemo(() => a + b, [a, b]);

This is unnecessary because a + b is already fast.

useMemo vs useCallback

Many beginners get confused between these two:

Hook Purpose
useMemo Memoizes a value
useCallback Memoizes a function

Example:


const result = useMemo(() => computeValue(a, b), [a, b]);
const handleClick = useCallback(() => {
 console.log("Clicked");
}, []);

Performance Tip

Use useMemo only when:

  • You notice performance issues
  • You have heavy computation
  • You are working with large data

Otherwise, React already optimizes small operations well.

Advantages of useMemo

✔ Improves performance
✔ Prevents unnecessary recalculations
✔ Optimizes rendering
✔ Useful for large-scale apps

Disadvantages of useMemo

❌ Can increase memory usage
❌ Overuse may reduce readability
❌ Not needed for simple logic

useMemo Hook – Interview Questions

Q 1: What is useMemo used for?
Ans: useMemo is used to memoize expensive computations to improve performance.
Q 2: How does useMemo work?
Ans: It recalculates the value only when its dependencies change.
Q 3: When should useMemo be used?
Ans: When a computation is expensive and causes performance issues.
Q 4: Does useMemo prevent re-rendering?
Ans: No, it prevents recalculations, not re-renders.
Q 5: Is useMemo always necessary?
Ans: No, overusing it can make code harder to maintain.

useMemo Hook – Objective Questions (MCQs)

Q1. What is the main purpose of the useMemo hook?






Q2. Which of the following is the correct syntax for useMemo?






Q3. When does a useMemo value recompute?






Q4. Which of these is NOT a use case for useMemo?






Q5. useMemo is used primarily in:






Conclusion

The useMemo Hook in React JS is a powerful optimization tool that helps improve application performance by caching expensive computations. It ensures that calculations are only re-executed when necessary, making your React apps faster and more efficient.

Continue Learning React