Popular Searches
Popular Course Categories
Popular Courses

useMemo Hook

useMemo Hook

Advanced React Hooks

useMemo Hook in React JS – Complete Detailed Notes

The useMemo Hook is a built-in React Hook that helps optimize application performance by caching the result of a calculation between re-renders. When the dependencies of a calculation have not changed, React can reuse the previously calculated value instead of performing the calculation again.

The useMemo Hook is particularly useful when working with large arrays, complex calculations, filtered lists, sorting operations, and optimized child components. It is a performance optimization tool and should be used when it provides a meaningful benefit.


1. Learning Objectives

After studying this topic, you will be able to:

  • Understand the purpose of the useMemo Hook.
  • Learn its syntax, parameters, and return value.
  • Understand memoization and dependency arrays.
  • Optimize expensive calculations in React components.
  • Use useMemo with arrays, objects, and filtered lists.
  • Understand the difference between useMemo, useCallback, and React.memo.
  • Identify common mistakes when using useMemo.
  • Apply useMemo in practical React projects.

2. What Is the useMemo Hook?

useMemo is a React Hook that caches the result of a calculation. React recalculates the value when one or more dependencies change. If the dependencies remain the same, React can reuse the cached result.

Syntax:

const cachedValue = useMemo(calculateValue, dependencies);

Explanation:

  • useMemo: The React Hook used for memoization.
  • calculateValue: A pure function that calculates and returns a value.
  • dependencies: An array containing every reactive value used by the calculation.
  • cachedValue: The result returned by the calculation or reused from the previous render.

React compares each dependency with its previous value using Object.is. If all dependencies are unchanged, React can reuse the previous result. If a dependency changes, React recalculates the value.

3. What Is Memoization?

Memoization is a programming technique that stores the result of a calculation so that the same work does not need to be repeated when its inputs have not changed.

For example, imagine calculating the total price of thousands of products. If a component re-renders because an unrelated theme setting changes, the total may not need to be recalculated if the product data remains unchanged.

Basic Example

function calculateSquare(number) {
  console.log('Calculating square...');
  return number * number;
}
const result = calculateSquare(5);
console.log(result);

The function calculates the square of 5 and returns 25. If the same calculation is repeatedly performed with the same input, memoization can help reuse the result.

In React, useMemo provides a way to cache such calculation results between renders.

4. Why Do We Need useMemo?

React components can re-render when their state changes, their props change, or their parent component re-renders. By default, calculations performed in the component body run again whenever that component renders.

Most calculations are inexpensive and do not need optimization. However, expensive calculations can make the interface feel slow when they are repeated unnecessarily.

The useMemo Hook can help when:

  • A calculation processes a large amount of data.
  • A component filters or sorts a large array.
  • A calculated object or array is passed to a memoized child component.
  • A calculated value is used as a dependency of another Hook.
  • Performance measurements show that a repeated calculation is costly.

5. Basic Example Without useMemo

Consider a component that calculates the square of a number.

import { useState } from 'react';
function SquareCalculator() {
  const [number, setNumber] = useState(5);
  const [theme, setTheme] = useState('light');
  function calculateSquare(value) {
    console.log('Calculating square...');
    return value * value;
  }
  const square = calculateSquare(number);
  return (
    <div className={theme}>
      <h2>Square Calculator</h2>
      <p>Number: {number}</p>
      <p>Square: {square}</p>
      <button onClick={() => setNumber(value => value + 1)}>
        Increase Number
      </button>
      <button onClick={() => setTheme(value => value === 'light' ? 'dark' : 'light')}>
        Change Theme
      </button>
    </div>
  );
}
export default SquareCalculator;

In this example, changing the theme causes the component to re-render. The square calculation runs again even though the number has not changed. For a simple calculation, this is usually not a performance problem, but it demonstrates the behavior.

6. Basic Example Using useMemo

We can use useMemo to cache the square calculation until the number changes.

import { useMemo, useState } from 'react';
function SquareCalculator() {
  const [number, setNumber] = useState(5);
  const [theme, setTheme] = useState('light');
  const square = useMemo(() => {
    console.log('Calculating square...');
    return number * number;
  }, [number]);
  return (
    <div className={theme}>
      <h2>Square Calculator</h2>
      <p>Number: {number}</p>
      <p>Square: {square}</p>
      <button onClick={() => setNumber(value => value + 1)}>
        Increase Number
      </button>
      <button onClick={() => setTheme(value => value === 'light' ? 'dark' : 'light')}>
        Change Theme
      </button>
    </div>
  );
}
export default SquareCalculator;

How it works:

  1. When the component first renders, React calculates the square.
  2. When the number changes, React recalculates the square.
  3. When only the theme changes, React can reuse the cached square.
  4. The component still re-renders when its state changes; useMemo only caches the calculation result.

7. Understanding the Dependency Array

The dependency array tells React which reactive values are used by the calculation. It is important to include every prop, state value, and component-scope variable or function used by the calculation.

Dependency Pattern Behavior
useMemo(() => calculate()) Recalculates on every render because no dependency array is supplied.
useMemo(() => calculate(), []) Reuses the cached result while the component remains mounted, assuming React retains the cache.
useMemo(() => calculate(), [value]) Recalculates when value changes.
useMemo(() => calculate(), [a, b]) Recalculates when either a or b changes.

Example With Multiple Dependencies

import { useMemo, useState } from 'react';
function PriceCalculator() {
  const [price, setPrice] = useState(100);
  const [quantity, setQuantity] = useState(2);
  const total = useMemo(() => {
    return price * quantity;
  }, [price, quantity]);
  return (
    <div>
      <p>Price: ₹{price}</p>
      <p>Quantity: {quantity}</p>
      <p>Total: ₹{total}</p>
      <button onClick={() => setPrice(value => value + 10)}>Increase Price</button>
      <button onClick={() => setQuantity(value => value + 1)}>Increase Quantity</button>
    </div>
  );
}
export default PriceCalculator;

The total is recalculated when the price or quantity changes. Because this multiplication is inexpensive, useMemo is not necessary in a real application; it is included here to demonstrate dependencies.

8. Using useMemo With Arrays

Filtering, sorting, and transforming large arrays can require significant computation. You can use useMemo to cache the result when the source array and relevant filter values remain unchanged.

Example: Filtering Products

import { useMemo, useState } from 'react';
const products = [
  { id: 1, name: 'Laptop', price: 50000 },
  { id: 2, name: 'Mouse', price: 700 },
  { id: 3, name: 'Keyboard', price: 1500 },
  { id: 4, name: 'Monitor', price: 12000 }
];
function ProductList() {
  const [search, setSearch] = useState('');
  const [showAffordable, setShowAffordable] = useState(false);
  const filteredProducts = useMemo(() => {
    return products.filter(product => {
      const matchesSearch = product.name
        .toLowerCase()
        .includes(search.toLowerCase());
      const matchesPrice = !showAffordable || product.price < 5000;
      return matchesSearch && matchesPrice;
    });
  }, [search, showAffordable]);
  return (
    <div>
      <h2>Product List</h2>
      <input
        value={search}
        onChange={event => setSearch(event.target.value)}
        placeholder="Search products"
      />
      <label>
        <input
          type="checkbox"
          checked={showAffordable}
          onChange={event => setShowAffordable(event.target.checked)}
        />
        Show products under ₹5,000
      </label>
      <ul>
        {filteredProducts.map(product => (
          <li key={product.id}>
            {product.name} - ₹{product.price}
          </li>
        ))}
      </ul>
    </div>
  );
}
export default ProductList;

The filtered list is recalculated when search or showAffordable changes. In this example, the product array is declared outside the component, so its reference remains stable.

9. Using useMemo With Sorting

Sorting data can be another useful example of memoization. The original array should not be mutated during rendering. Create a copy before sorting.

import { useMemo, useState } from 'react';
function StudentList({ students }) {
  const [order, setOrder] = useState('ascending');
  const sortedStudents = useMemo(() => {
    return [...students].sort((a, b) => {
      return order === 'ascending'
        ? a.name.localeCompare(b.name)
        : b.name.localeCompare(a.name);
    });
  }, [students, order]);
  return (
    <div>
      <button onClick={() => setOrder(value =>
        value === 'ascending' ? 'descending' : 'ascending'
      )}>
        Change Sort Order
      </button>
      <ul>
        {sortedStudents.map(student => (
          <li key={student.id}>{student.name}</li>
        ))}
      </ul>
    </div>
  );
}
export default StudentList;

Important: This example assumes the parent supplies a stable students array reference when the underlying data has not changed. If the parent creates a new array on every render, the memoized calculation will run again.

10. Using useMemo With Objects

JavaScript creates a new object reference when an object literal is evaluated. If an object is expensive to calculate or is passed to a memoized child component, useMemo can preserve its reference while its dependencies remain unchanged.

import { useMemo, useState } from 'react';
function UserSettings() {
  const [username, setUsername] = useState('Alex');
  const [theme, setTheme] = useState('light');
  const settings = useMemo(() => ({
    username,
    theme
  }), [username, theme]);
  return (
    <div>
      <p>Username: {settings.username}</p>
      <p>Theme: {settings.theme}</p>
      <button onClick={() => setUsername('Jordan')}>Change Username</button>
      <button onClick={() => setTheme(value => value === 'light' ? 'dark' : 'light')}>Change Theme</button>
    </div>
  );
}
export default UserSettings;

Here, the object is recreated when either dependency changes. Since both dependencies are displayed and used in the object, both belong in the dependency array.

11. useMemo and Child Component Rendering

The useMemo Hook can help a memoized child component skip unnecessary re-renders by preserving the reference of a calculated array or object when its inputs remain unchanged.

import { memo, useMemo, useState } from 'react';
const ProductDisplay = memo(function ProductDisplay({ products }) {
  console.log('ProductDisplay rendered');
  return (
    <ul>
      {products.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
});
function App() {
  const [theme, setTheme] = useState('light');
  const [count, setCount] = useState(0);
  const products = useMemo(() => [
    { id: 1, name: 'Laptop' },
    { id: 2, name: 'Mouse' }
  ], []);
  return (
    <div className={theme}>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(value => value + 1)}>Increase Count</button>
      <button onClick={() => setTheme(value => value === 'light' ? 'dark' : 'light')}>Change Theme</button>
      <ProductDisplay products={products} />
    </div>
  );
}
export default App;

Because products retains the same reference while the dependencies remain unchanged, ProductDisplay can skip re-rendering when its props are unchanged. The child may still render if its own state or context changes, or if React otherwise needs to render it.

12. useMemo vs useCallback vs React.memo

Feature useMemo useCallback React.memo
Purpose Caches a calculation result. Caches a function reference. Can skip re-rendering a component when its props are unchanged.
Used for Calculated values, arrays, and objects. Functions passed to optimized children or used as dependencies. Optimizing child component rendering.
Syntax useMemo(() => value, [deps]) useCallback(fn, [deps]) memo(Component)
Returns The cached calculation result. The cached function reference. A memoized component type.
Example Cache a filtered product list. Cache a submit handler. Optimize a product display component.

Example of useCallback

import { useCallback, useState } from 'react';
function SearchPage() {
  const [query, setQuery] = useState('');
  const handleSearch = useCallback(() => {
    console.log('Searching for:', query);
  }, [query]);
  return (
    <div>
      <input value={query} onChange={event => setQuery(event.target.value)} />
      <button onClick={handleSearch}>Search</button>
    </div>
  );
}
export default SearchPage;

useCallback is designed for function references. Use useMemo when you need to cache a calculated value.

13. Common Mistakes When Using useMemo

Mistake 1: Using useMemo for Every Calculation

Not every calculation needs memoization. Simple calculations, such as adding two numbers or creating a short string, are usually inexpensive.

Simple approach:

const total = price * quantity;

Use useMemo when the calculation is expensive or when preserving a value's reference serves a specific optimization purpose.

Mistake 2: Forgetting the Dependency Array

Without a dependency array, the calculation runs on every render.

Incorrect for caching between renders:

const result = useMemo(() => expensiveCalculation(data));

Correct:

const result = useMemo(
  () => expensiveCalculation(data),
  [data]
);

Mistake 3: Missing Dependencies

Every reactive value used by the calculation must be included in the dependency array. Missing dependencies can cause the cached value to be based on outdated data.

Incorrect:

const total = useMemo(() => price * quantity, [price]);

Correct:

const total = useMemo(() => price * quantity, [price, quantity]);

Mistake 4: Calling useMemo Inside a Condition or Loop

Hooks must be called at the top level of a function component or custom Hook. Do not call useMemo inside a condition, loop, or nested callback.

Incorrect:

if (enabled) {
  const value = useMemo(() => calculateValue(), [enabled]);
}

Correct:

const value = useMemo(() => {
  return enabled ? calculateValue() : 0;
}, [enabled]);

Mistake 5: Performing Side Effects Inside useMemo

The calculation passed to useMemo should be pure. Do not use it for API requests, updating the DOM, setting timers, or changing external variables.

Incorrect:

const result = useMemo(() => {
  fetch('/api/products');
  return products.length;
}, [products]);

Use an event handler or an appropriate Effect for external side effects. Use useMemo to calculate and return values.

Mistake 6: Forgetting to Return a Value

If the calculation function does not return a value, the result will usually be undefined.

Incorrect:

const doubled = useMemo(() => {
  numbers.map(number => number * 2);
}, [numbers]);

Correct:

const doubled = useMemo(() => {
  return numbers.map(number => number * 2);
}, [numbers]);

Mistake 7: Expecting useMemo to Prevent All Re-Renders

useMemo caches a value; it does not stop its component from rendering. To optimize a child component's rendering, React.memo may be useful when its props remain unchanged.

Mistake 8: Mutating Data Inside the Calculation

Do not mutate an input array or object while calculating a memoized value.

Incorrect:

const sortedItems = useMemo(() => {
  return items.sort((a, b) => a.price - b.price);
}, [items]);

Correct:

const sortedItems = useMemo(() => {
  return [...items].sort((a, b) => a.price - b.price);
}, [items]);

Mistake 9: Relying on useMemo for Correctness

React documents useMemo as a performance optimization rather than a guarantee that a value will remain cached forever. Your application should still work correctly if React recalculates the value. Do not use it as a replacement for state or refs when persistent storage is required.

14. Rules of the useMemo Hook

  • Call useMemo only at the top level of a function component or custom Hook.
  • Do not call it inside loops, conditions, or nested functions.
  • Pass a calculation function that returns the required value.
  • Include all reactive values used by the calculation in the dependency array.
  • Keep the calculation pure and free from side effects.
  • Do not mutate existing state, props, or input arrays during the calculation.
  • Use memoization only when it provides a meaningful performance benefit.
  • Do not rely on the cached value for application correctness.

15. Understanding React Strict Mode

When React Strict Mode is enabled in development, React may call a useMemo calculation function twice to help detect accidental impurities. One of the results is ignored. This additional development behavior does not mean the calculation should perform side effects.

For example, a pure calculation such as items.filter(item => item.active) can safely run more than once. A calculation that modifies a global variable or mutates the input array is not pure and should be corrected.

16. Performance Considerations

useMemo does not make the initial render faster because React must calculate the initial value. It can help on later renders by avoiding repeated calculations when dependencies remain unchanged.

Before adding memoization:

  1. Identify the calculation or interaction that appears slow.
  2. Measure performance with suitable developer tools.
  3. Check whether the calculation is repeated unnecessarily.
  4. Add useMemo when caching is likely to help.
  5. Measure again to confirm the improvement.

React Compiler can automatically memoize values and functions in supported configurations, reducing the need for manual memoization. Follow your project's React setup and compiler configuration.

17. Practical Project: Product Search and Filter

Create a product listing page that allows users to search products, filter by category, and sort products by price. Use useMemo to cache the filtered and sorted product list.

Project Requirements

  • Store the search term using useState.
  • Store the selected category using useState.
  • Store the sort order using useState.
  • Filter products according to the search term and category.
  • Sort the filtered results by price.
  • Use useMemo to cache the resulting list.
  • Use stable product IDs as list keys.

Sample Code

import { useMemo, useState } from 'react';
const products = [
  { id: 1, name: 'Laptop', category: 'Electronics', price: 50000 },
  { id: 2, name: 'Mouse', category: 'Accessories', price: 700 },
  { id: 3, name: 'Keyboard', category: 'Accessories', price: 1500 },
  { id: 4, name: 'Monitor', category: 'Electronics', price: 12000 },
  { id: 5, name: 'Headphones', category: 'Accessories', price: 2500 }
];
function ProductSearch() {
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState('All');
  const [sortOrder, setSortOrder] = useState('ascending');
  const visibleProducts = useMemo(() => {
    const filtered = products.filter(product => {
      const matchesSearch = product.name
        .toLowerCase()
        .includes(search.toLowerCase());
      const matchesCategory =
        category === 'All' || product.category === category;
      return matchesSearch && matchesCategory;
    });
    return [...filtered].sort((a, b) => {
      return sortOrder === 'ascending'
        ? a.price - b.price
        : b.price - a.price;
    });
  }, [search, category, sortOrder]);
  return (
    <div>
      <h2>Product Search</h2>
      <input
        value={search}
        onChange={event => setSearch(event.target.value)}
        placeholder="Search products"
      />
      <select value={category} onChange={event => setCategory(event.target.value)}>
        <option value="All">All Categories</option>
        <option value="Electronics">Electronics</option>
        <option value="Accessories">Accessories</option>
      </select>
      <select value={sortOrder} onChange={event => setSortOrder(event.target.value)}>
        <option value="ascending">Price: Low to High</option>
        <option value="descending">Price: High to Low</option>
      </select>
      <ul>
        {visibleProducts.map(product => (
          <li key={product.id}>
            {product.name} - {product.category} - ₹{product.price}
          </li>
        ))}
      </ul>
      {visibleProducts.length === 0 && <p>No products found.</p>}
    </div>
  );
}
export default ProductSearch;

Project explanation: The calculation depends on search, category, and sortOrder. If none of these values changes, React can reuse the cached result. The source product array is declared outside the component, so it does not receive a new reference on every render.

18. Interview Questions and Answers

Q1. What is the useMemo Hook?

useMemo is a React Hook that caches the result of a calculation between re-renders until its dependencies change.

Q2. What is memoization?

Memoization is a technique that stores a calculation result and reuses it when the inputs remain unchanged.

Q3. What is the syntax of useMemo?

const value = useMemo(() => calculateValue(), [dependency]);

Q4. What is the purpose of the dependency array?

It identifies the reactive values used by the calculation. React compares them with their previous values and recalculates when one or more change.

Q5. Does useMemo prevent a component from re-rendering?

No. It caches a calculated value. The component can still re-render when its state, props, or context changes.

Q6. What happens if the dependency array is omitted?

The calculation runs on every render, so the Hook does not provide caching between renders in that case.

Q7. Can useMemo be used with arrays and objects?

Yes. It can cache calculated arrays and objects, which can be helpful when the calculation is expensive or stable references are useful for optimization.

Q8. What is the difference between useMemo and useCallback?

useMemo caches a calculation result, while useCallback caches a function reference.

Q9. What is the difference between useMemo and React.memo?

useMemo caches a value within a component. React.memo can skip rendering a child component when its props remain unchanged.

Q10. Can useMemo perform API calls?

No. The calculation should be pure and should not perform side effects. Use an appropriate Effect or event handler for API requests.

Q11. Should useMemo be used for every calculation?

No. Use it when a calculation is expensive or when caching a stable reference provides a specific optimization benefit.

Q12. Is the cached value guaranteed to remain forever?

No. React treats memoization as a performance optimization and may discard the cache in certain circumstances. Application correctness should not depend on the cache being permanent.

19. Practice Exercises

  1. Create a calculator that uses useMemo to calculate the area of a rectangle.
  2. Create a student list that can be sorted alphabetically.
  3. Build a product list with search and category filters.
  4. Calculate the total price of a shopping cart from its items.
  5. Use useMemo to filter a large array of employee records.
  6. Combine useMemo with React.memo to optimize a child component.
  7. Compare the performance of a calculation with and without memoization.
  8. Find and correct missing dependencies in a memoized calculation.

20. Quick Revision Checklist

  • ☑ useMemo caches a calculation result.
  • ☑ Its syntax is useMemo(calculateValue, dependencies).
  • ☑ The calculation function should be pure and return a value.
  • ☑ Every reactive value used by the calculation belongs in the dependency array.
  • ☑ React compares dependencies using Object.is.
  • ☑ The calculation runs again when dependencies change.
  • ☑ useMemo does not prevent the component itself from rendering.
  • ☑ It can optimize expensive filtering, sorting, and transformation operations.
  • ☑ It can preserve object or array references for memoized child components.
  • ☑ It should not be used for side effects.
  • ☑ It should not be called conditionally or inside loops.
  • ☑ Memoization is an optimization, not a correctness guarantee.

21. Official React Documentation

22. React JS Training and Course Demo

To strengthen your React JS knowledge, explore the React JS training course and review the course details. You can also register for a course demo to learn more about the training.

23. Conclusion

The useMemo Hook helps improve React application performance by caching calculation results between renders. It is especially useful for expensive calculations, filtered and sorted lists, and preserving references passed to optimized child components.

To use useMemo correctly, follow the Rules of Hooks, include all required dependencies, keep calculations pure, and measure performance before adding optimizations. For simple calculations, direct computation is often easier to read and maintain. Use memoization when it solves a real performance problem.

Previous Next
whatsapp