useMemo for Expensive Calculations in React – Complete Notes
1. Introduction to useMemo
useMemo is a React Hook that allows developers to cache the result of a calculation between renders. It is useful when a component performs expensive calculations that do not need to be repeated if their dependencies have not changed.
In React, a component may re-render when its state or props change. During rendering, JavaScript calculations inside the component run again. If a calculation involves processing a large array, filtering thousands of records, sorting complex data, or performing mathematical operations, repeating it unnecessarily may affect performance.
The useMemo Hook helps avoid this repeated calculation by reusing a previously calculated value while its dependencies remain unchanged.
2. Syntax of useMemo
const memoizedValue = useMemo(() => {
return calculateValue();
}, [dependencies]);
Explanation:
useMemo: React Hook used to cache a calculation result.
() => calculateValue(): A function that performs the calculation.
[dependencies]: Values that determine when the calculation needs to run again.
memoizedValue: The cached result returned by the Hook.
React runs the calculation function during rendering when needed. If the dependencies are unchanged from the previous render, React can reuse the cached result instead of running the calculation again.
3. Why Do We Need useMemo?
Without useMemo, calculations written directly inside a component execute whenever that component renders. This can become inefficient when a calculation takes significant time or processing power.
Consider an application that displays thousands of products. When the user changes an unrelated setting, the component might render again and repeat the same filtering or sorting operation even though the product data and search criteria have not changed.
Using useMemo can help avoid that unnecessary work.
- Reduces repeated expensive calculations.
- Can improve performance in data-heavy components.
- Helps cache filtered and sorted results.
- Can maintain stable object or array references between renders.
- Can support optimized child components when stable props are useful.
4. Understanding Expensive Calculations
An expensive calculation is an operation that requires a noticeable amount of processing time or computational resources. Whether a calculation is expensive depends on the amount of data, the algorithm, and the environment in which the application runs.
Common examples include:
- Filtering thousands of products or users.
- Sorting large arrays of records.
- Calculating statistics from large datasets.
- Generating complex charts from raw data.
- Performing repeated mathematical computations.
- Transforming API response data into a format suitable for display.
Simple operations, such as adding two numbers or displaying a short string, generally do not require useMemo because memoization can add unnecessary complexity.
5. Example Without useMemo
In this example, the component calculates the sum of numbers whenever it renders. Changing the counter also causes the component to render again, so the calculation runs again even though the array has not changed.
import React, { useState } from "react";
function App() {
const [count, setCount] = useState(0);
const numbers = [10, 20, 30, 40, 50];
const calculateTotal = () => {
console.log("Calculating total...");
return numbers.reduce((total, number) => total + number, 0);
};
const total = calculateTotal();
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase Counter
</button>
<h2>Total: {total}</h2>
</div>
);
}
export default App;
Explanation: Every time the counter changes, App renders again and calls calculateTotal again. Although this calculation is small, the same pattern can be inefficient when the calculation processes a large dataset.
6. Example Using useMemo
We can use useMemo to cache the calculated total. The calculation will be repeated only when the numbers dependency changes, rather than whenever the counter changes.
import React, { useMemo, useState } from "react";
function App() {
const [count, setCount] = useState(0);
const numbers = [10, 20, 30, 40, 50];
const total = useMemo(() => {
console.log("Calculating total...");
return numbers.reduce((sum, number) => sum + number, 0);
}, [numbers]);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase Counter
</button>
<h2>Total: {total}</h2>
</div>
);
}
export default App;
Important note: This example creates a new numbers array on every render, so its reference changes and the calculation will run again. To demonstrate effective memoization, the array must have a stable reference or be derived from stable dependencies.
Improved example:
import React, { useMemo, useState } from "react";
const numbers = [10, 20, 30, 40, 50];
function App() {
const [count, setCount] = useState(0);
const total = useMemo(() => {
console.log("Calculating total...");
return numbers.reduce((sum, number) => sum + number, 0);
}, []);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<h2>Total: {total}</h2>
</div>
);
}
export default App;
In this improved example, numbers is declared outside the component, so its reference remains stable. The empty dependency array indicates that the calculation has no reactive dependencies and can be reused across renders. React may still call the calculation more than once in development Strict Mode or discard a cached value in certain situations, so useMemo should be treated as a performance optimization rather than a semantic guarantee.
7. How useMemo Works
The useMemo Hook compares the current dependencies with the dependencies from the previous render using React's dependency comparison. If the dependencies have not changed, React can reuse the cached value.
- The component renders.
- React evaluates the dependencies provided to useMemo.
- If this is the initial render, React runs the calculation function.
- React stores the calculation result for possible reuse.
- On a later render, React compares the new dependencies with the previous dependencies.
- If the dependencies are unchanged, React can return the cached value.
- If a dependency changes, React runs the calculation again and caches the new result.
Example:
const result = useMemo(() => {
return price * quantity;
}, [price, quantity]);
Here, React can reuse result when both price and quantity remain unchanged. If either dependency changes, React recalculates the result.
8. useMemo for Filtering Large Arrays
Filtering is a common use case for useMemo. For example, an application may display thousands of products and allow users to search by product name.
import React, { useMemo, useState } from "react";
const products = [
{ id: 1, name: "Laptop" },
{ id: 2, name: "Mobile Phone" },
{ id: 3, name: "Keyboard" },
{ id: 4, name: "Laptop Stand" }
];
function ProductSearch() {
const [search, setSearch] = useState("");
const [count, setCount] = useState(0);
const filteredProducts = useMemo(() => {
console.log("Filtering products...");
return products.filter(product =>
product.name.toLowerCase().includes(search.toLowerCase())
);
}, [search]);
return (
<div>
<input
value={search}
onChange={event => setSearch(event.target.value)}
placeholder="Search products"
/>
<button onClick={() => setCount(c => c + 1)}>
Counter: {count}
</button>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
export default ProductSearch;
Explanation: The filtering calculation runs when the search value changes. Clicking the counter button does not change the search dependency, so React can reuse the filtered results.
9. useMemo for Sorting Data
Sorting a large dataset can be computationally expensive. useMemo can cache sorted data until the source data or sorting option changes.
import React, { useMemo, useState } from "react";
const initialScores = [85, 45, 92, 67, 78, 55];
function ScoreList() {
const [ascending, setAscending] = useState(true);
const [count, setCount] = useState(0);
const sortedScores = useMemo(() => {
console.log("Sorting scores...");
return [...initialScores].sort((a, b) =>
ascending ? a - b : b - a
);
}, [ascending]);
return (
<div>
<button onClick={() => setAscending(value => !value)}>
Toggle Sorting
</button>
<button onClick={() => setCount(value => value + 1)}>
Counter: {count}
</button>
<ul>
{sortedScores.map((score, index) => (
<li key={index}>{score}</li>
))}
</ul>
</div>
);
}
export default ScoreList;
Explanation: The array is sorted when ascending changes. The spread operator creates a copy before sorting, preventing the original array from being mutated. Updating the counter does not require sorting again.
10. useMemo with Multiple Dependencies
A calculation can depend on several state variables or props. Every reactive value used by the calculation should be included in the dependency array.
import React, { useMemo, useState } from "react";
function ShoppingCart() {
const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
return (
<div>
<p>Price: ₹{price}</p>
<button onClick={() => setPrice(p => p + 10)}>
Increase Price
</button>
<p>Quantity: {quantity}</p>
<button onClick={() => setQuantity(q => q + 1)}>
Increase Quantity
</button>
<h2>Total: ₹{total}</h2>
</div>
);
}
export default ShoppingCart;
When either price or quantity changes, React recalculates the total. If neither changes, React can reuse the previous result. This multiplication is inexpensive, so the example illustrates dependency behavior rather than a situation where memoization is necessarily beneficial.
11. useMemo with Objects
useMemo can also cache an object that is passed to a child component or used as a dependency elsewhere. This can be useful when preserving object identity helps avoid unnecessary work.
import React, { useMemo, useState } from "react";
function UserProfile() {
const [count, setCount] = useState(0);
const user = useMemo(() => ({
name: "Amit",
role: "Developer"
}), []);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
<h2>{user.name}</h2>
<p>{user.role}</p>
</div>
);
}
export default UserProfile;
In this example, the user object can retain the same reference between renders. This is useful if the object is passed to a memoized child or used in another Hook's dependency array. For simple values that are used only in the same component, useMemo may not be necessary.
12. Difference Between useMemo and useCallback
| Feature |
useMemo |
useCallback |
| Purpose |
Caches the result of a calculation. |
Caches a function reference. |
| Returns |
The calculated value. |
The function itself. |
| Common use |
Filtering, sorting, or transforming data. |
Passing stable callbacks to memoized children. |
| Syntax |
useMemo(() => calculate(), [deps]) |
useCallback(functionName, [deps]) |
13. Difference Between useMemo and React.memo
| Feature |
useMemo |
React.memo |
| Type |
React Hook |
Higher-order component |
| Primary purpose |
Caches a calculation result. |
Can skip a component render when its props are unchanged. |
| Applied to |
A value or calculation inside a component. |
A component definition. |
| Example |
useMemo(() => items.filter(...), [items]) |
React.memo(ProductCard) |
14. Common Mistakes When Using useMemo
- Using it for every calculation: Small calculations may be faster without memoization.
- Missing dependencies: Leaving out reactive values can result in stale calculations.
- Unstable dependencies: Creating a new object or array on every render can cause the calculation to run again.
- Mutating arrays or objects: Mutating existing data can interfere with dependency comparisons and produce unexpected results.
- Expecting permanent caching: React may discard cached values in certain circumstances.
- Using it for side effects: useMemo is intended for pure calculations, not API requests, subscriptions, or other side effects.
- Ignoring performance measurements: Memoization should solve a real performance issue rather than add unnecessary complexity.
15. Best Practices for useMemo
- Use useMemo when a calculation is expensive enough to justify caching.
- Include every reactive value used by the calculation in the dependency array.
- Keep the calculation pure so it returns the same result for the same inputs.
- Avoid mutating arrays and objects used in calculations.
- Keep dependencies stable where practical.
- Use the React Profiler to identify performance bottlenecks.
- Compare performance before and after adding memoization.
- Do not rely on useMemo for correctness; your component should remain correct if React recalculates the value.
16. Practical Project: Product Filtering and Sorting
Project objective: Build a product list that lets users search for products and sort them by price while avoiding repeated filtering and sorting when unrelated state changes.
import React, { useMemo, useState } from "react";
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mobile Phone", price: 25000 },
{ id: 3, name: "Keyboard", price: 1500 },
{ id: 4, name: "Monitor", price: 12000 },
{ id: 5, name: "Headphones", price: 3000 }
];
function ProductList() {
const [search, setSearch] = useState("");
const [sortOrder, setSortOrder] = useState("low");
const [count, setCount] = useState(0);
const filteredAndSortedProducts = useMemo(() => {
console.log("Filtering and sorting products...");
return products
.filter(product =>
product.name.toLowerCase().includes(search.toLowerCase())
)
.sort((a, b) =>
sortOrder === "low"
? a.price - b.price
: b.price - a.price
);
}, [search, sortOrder]);
return (
<div>
<h1>Product Store</h1>
<input
value={search}
onChange={event => setSearch(event.target.value)}
placeholder="Search products"
/>
<select
value={sortOrder}
onChange={event => setSortOrder(event.target.value)}
>
<option value="low">Price: Low to High</option>
<option value="high">Price: High to Low</option>
</select>
<button onClick={() => setCount(c => c + 1)}>
Counter: {count}
</button>
<ul>
{filteredAndSortedProducts.map(product => (
<li key={product.id}>
{product.name} - ₹{product.price}
</li>
))}
</ul>
</div>
);
}
export default ProductList;
Project explanation: The product list is filtered and sorted when search or sortOrder changes. Updating the counter does not change either dependency, so React can reuse the cached result. The products array is declared outside the component, keeping its reference stable.
17. Interview Questions and Answers
Q1. What is useMemo in React?
Answer: useMemo is a React Hook that caches the result of a calculation between renders when its dependencies remain unchanged.
Q2. Why is useMemo used for expensive calculations?
Answer: It can prevent React from repeating an expensive calculation when the inputs to that calculation have not changed.
Q3. What is the syntax of useMemo?
Answer: const value = useMemo(() => calculateValue(), [dependencies]);
Q4. What happens when a dependency changes?
Answer: React runs the calculation again and caches the updated result for possible reuse.
Q5. Can useMemo improve application performance?
Answer: Yes, when it avoids enough repeated work to outweigh the overhead of memoization. Performance should be measured.
Q6. Can useMemo be used for API calls?
Answer: No. useMemo is for pure calculations. API calls and other side effects should be handled with appropriate event handlers, data-fetching solutions, or Effects when needed.
Q7. What happens if the dependency array is empty?
Answer: React can reuse the cached result across renders because there are no reactive dependencies. The calculation runs on the initial render, though development Strict Mode or cache invalidation can result in additional calculations.
Q8. What happens if the dependency array is omitted?
Answer: If the dependency array is omitted, the calculation runs during every render, so useMemo does not avoid recalculating the value on subsequent renders.
Q9. Is useMemo a guarantee that a calculation runs only once?
Answer: No. It is a performance optimization, and React may run the calculation again when needed or discard the cached value.
Q10. How do you decide whether to use useMemo?
Answer: Profile the application, identify expensive calculations, and measure whether caching the result improves performance.
18. Summary
useMemo is an important React Hook for optimizing components that perform expensive calculations. It caches calculation results while dependencies remain unchanged, helping avoid unnecessary filtering, sorting, and data processing. It should be used thoughtfully, with correct dependencies and pure calculations, and should not replace performance measurement or be relied upon for application correctness.
19. Learn React JS with JustAcademy
Learn React fundamentals, Hooks, component optimization, state management, and practical front-end development through structured training and hands-on projects.
JustAcademy React JS Training
Explore the course and register for a demo session using the link below.
Register for React JS Course Demo