Optimizing Calculations with useMemo
React applications frequently perform calculations while rendering. For example, a student management application may filter thousands of student records, sort course information, calculate fee totals, or process other large collections of data.
When a component renders again because its state changes, these calculations normally execute again. If the calculation is expensive and its inputs have not changed, repeating the same work may waste processing time.
React provides the useMemo Hook to cache the result of a calculation between renders. When the dependencies remain unchanged, React can reuse the previous result instead of executing the calculation again.
1. What Is useMemo?
useMemo is a React Hook that lets you cache the result of a calculation between renders. React calls the calculation function when necessary and can reuse the previously calculated value when its dependencies have not changed.
Suppose an institute maintains 5,000 student records. A user types a search term to find a student. Filtering the records may require processing many entries. If another unrelated state value changes, repeating the same filtering operation may be unnecessary.
With useMemo, the filtered list can be reused while the search term and student data remain unchanged.
If a dependency changes, React recalculates the value.
2. Syntax of useMemo
To use useMemo, import it from React and provide a calculation function followed by a dependency array.
import { useMemo } from "react";
const result = useMemo(() => {
return performCalculation();
}, [dependency1, dependency2]);
The syntax contains three important parts:
- Calculation function: Performs the calculation and returns the value to be cached.
- Dependency array: Contains the reactive values used by the calculation.
- Returned result: The calculated value that the component uses to display its UI.
Understanding the Dependency Array
| Syntax | Behavior |
|---|---|
useMemo(() => calculate(), [value]) |
The calculation can be reused while value remains unchanged. |
useMemo(() => calculate(), []) |
No reactive dependencies are listed. The cached result can be reused across ordinary re-renders. |
useMemo(() => calculate()) |
Without a dependency array, the calculation runs on every render. |
3. Example Without useMemo
First, consider a component that calculates the total of five numbers. The component also contains a counter. Whenever the counter changes, React renders the component again, and the total calculation runs again.
In this example, the numbers array is declared outside the component. This keeps the input data stable so that we can compare the normal calculation with the memoized calculation fairly.
import { useState } from "react";
const numbers = [10, 20, 30, 40, 50];
function calculateTotal(numbers) {
console.log("Calculating total...");
return numbers.reduce((total, number) => {
return total + number;
}, 0);
}
function CalculationExample() {
const [count, setCount] = useState(0);
const total = calculateTotal(numbers);
return (
<div>
<h2>Total: {total}</h2>
<h3>Counter: {count}</h3>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
</div>
);
}
export default CalculationExample;
Expected Output
Total: 150
Counter: 0
Button: Increase Counter
When the user clicks Increase Counter, the counter updates and the message "Calculating total..." appears again because the calculation runs during the next render.
Step-by-Step Explanation
- React renders the CalculationExample component.
- calculateTotal adds 10, 20, 30, 40, and 50.
- The calculation returns 150.
- The user clicks Increase Counter.
- setCount updates the counter and causes another render.
- calculateTotal executes again, although the numbers have not changed.
4. Example With useMemo
Now we will optimize the previous example using useMemo. Because the numbers array is a module-level constant, it does not change between renders. Therefore, an empty dependency array is appropriate for this particular calculation.
import { useMemo, useState } from "react";
const numbers = [10, 20, 30, 40, 50];
function calculateTotal(numbers) {
console.log("Calculating total...");
return numbers.reduce((total, number) => {
return total + number;
}, 0);
}
function CalculationExample() {
const [count, setCount] = useState(0);
const total = useMemo(() => {
return calculateTotal(numbers);
}, []);
return (
<div>
<h2>Total: {total}</h2>
<h3>Counter: {count}</h3>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
</div>
);
}
export default CalculationExample;
Expected Behavior
Initial display: Total: 150, Counter: 0.
After one click: Total: 150, Counter: 1.
After two clicks: Total: 150, Counter: 2.
The counter changes normally, but React can reuse the cached total instead of recalculating it on every counter update.
What Changed?
- The calculateTotal function is called inside useMemo.
- The dependency array is empty because the numbers array is constant.
- The calculation result is stored as the memoized value.
- Counter updates do not change the calculation dependencies.
5. Practical Example: Filtering Students
A student management system may contain many student records. Users need to search for a particular student by name. We can use useMemo to cache the filtered list while the search term remains unchanged.
import { useMemo, useState } from "react";
const students = [
"Samadhan",
"Samiksha",
"Aarav",
"Priya",
"Rahul",
"Sneha"
];
function StudentSearch() {
const [search, setSearch] = useState("");
const [count, setCount] = useState(0);
const filteredStudents = useMemo(() => {
console.log("Filtering students...");
return students.filter(student =>
student.toLowerCase().includes(
search.toLowerCase()
)
);
}, [search]);
return (
<div>
<h2>CIIT Training Institute
<ul>
{filteredStudents.map(student => (
<li key={student}>{student}</li>
))}
</ul>
</div>
);
}
export default StudentSearch;
How Does This Example Work?
- The students array contains six student names.
- The search state stores the text entered by the user.
- useMemo filters the student list using the current search value.
- When the search value changes, the calculation runs again.
- When only the counter changes, the search dependency remains unchanged.
- React can reuse the previously filtered list during the counter update.
Expected Output
Initially: All six students are displayed.
When the user searches for "Sam":
- Samadhan
- Samiksha
Clicking the counter does not require the student filtering calculation to run again. Changing the search text recalculates the filtered result.
6. Practical Example: Sorting Products
Consider an application displaying products with their prices. Users can sort the products from lowest to highest price or from highest to lowest price. The sorting calculation needs to run when the sort order changes, but not necessarily when an unrelated counter changes.
import { useMemo, useState } from "react";
const products = [
{ id: 1, name: "Keyboard", price: 1200 },
{ id: 2, name: "Mouse", price: 500 },
{ id: 3, name: "Monitor", price: 8500 },
{ id: 4, name: "Headphones", price: 1800 }
];
function ProductList() {
const [ascending, setAscending] = useState(true);
const [count, setCount] = useState(0);
const sortedProducts = useMemo(() => {
return [...products].sort((a, b) => {
return ascending
? a.price - b.price
: b.price - a.price;
});
}, [ascending]);
return (
<div>
<h2>Product List</h2>
<button onClick={() => setAscending(value => !value)}>
Toggle Sort Order
</button>
<button onClick={() => setCount(c => c + 1)}>
Counter: {count}
</button>
<ul>
{sortedProducts.map(product => (
<li key={product.id}>
{product.name} - ₹{product.price}
</li>
))}
</ul>
</div>
);
}
export default ProductList;
Expected Output: Ascending Price
- Mouse — ₹500
- Keyboard — ₹1200
- Headphones — ₹1800
- Monitor — ₹8500
Understanding the Dependencies
The sortedProducts calculation depends on ascending. When the user clicks Toggle Sort Order, ascending changes and React recalculates the sorted list. When only the counter changes, ascending remains the same and React can reuse the cached result.
7. Understanding Dependencies Correctly
The dependency array tells React which reactive values are used by the calculation. If any dependency changes, React recalculates the result. Dependencies are compared using Object.is.
import { useMemo, useState } from "react";
function PriceCalculator() {
const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const total = useMemo(() => {
console.log("Calculating total...");
return price * quantity;
}, [price, quantity]);
return (
<div>
<h2>Price: ₹{price}</h2>
<h2>Quantity: {quantity}</h2>
<h2>Total: ₹{total}</h2>
<button onClick={() => setPrice(p => p + 10)}>
Increase Price
</button>
<button onClick={() => setQuantity(q => q + 1)}>
Increase Quantity
</button>
</div>
);
}
export default PriceCalculator;
Expected Output
Initial values: Price ₹100, Quantity 2, Total ₹200.
After Increase Price: Price ₹110, Quantity 2, Total ₹220.
After Increase Quantity: Price ₹110, Quantity 3, Total ₹330.
Both price and quantity are included in the dependency array because the calculation uses both values. If either changes, React recalculates the total so that the displayed result remains correct.
8. useMemo vs useState
Although both Hooks are used inside function components, they have different purposes. useState stores information that changes over time, while useMemo caches the result of a calculation based on existing values.
| Feature | useState | useMemo |
|---|---|---|
| Main purpose | Store component state. | Cache a calculation result. |
| Typical values | Counter, search text, selected tab. | Filtered list, sorted list, calculated total. |
| Update behavior | Calling the state setter requests an update. | React recalculates when dependencies change. |
| Role in correctness | Stores application state. | Should remain safe to recalculate. |
9. useMemo vs React.memo
These two APIs are related to memoization, but they optimize different things. React.memo can skip rendering a component when its props are unchanged, whereas useMemo caches the result of a calculation.
| React.memo | useMemo |
|---|---|
| Memoizes a component. | Memoizes a calculation result. |
| Can skip a child render when its props are unchanged. | Can reuse a value when its dependencies are unchanged. |
| Useful for suitable child components. | Useful for expensive calculations and derived values. |
memo(Component) |
useMemo(() => calculate(), [dependency]) |
10. Common Mistakes with useMemo
Mistake 1: Using useMemo for Every Calculation
Small calculations may be faster to run directly. Memoization adds complexity, so use it when there is a meaningful performance reason.
Mistake 2: Missing Dependencies
If the calculation uses a changing state or prop that is missing from the dependency array, the cached result can become outdated.
Mistake 3: Unstable Dependencies
Creating a new object or array inside the component and using it as a dependency can cause the calculation to run again on every render because its reference changes.
Mistake 4: Mutating Existing Data
A useMemo calculation should be pure. Avoid changing external variables or mutating existing arrays and objects while rendering. Create a copy when an operation such as sorting would otherwise modify the original array.
Mistake 5: Treating the Cache as Permanent Storage
useMemo is a performance optimization, not a replacement for state, refs, or persistent storage. React may recalculate the value when needed.
11. Best Practices
- Use useMemo when a calculation is expensive enough to matter.
- Include all reactive dependencies used by the calculation.
- Keep calculations pure and avoid mutating existing data.
- Use React Developer Tools Profiler to identify actual bottlenecks.
- Measure performance before and after applying an optimization.
- Keep the code simple when memoization provides no meaningful benefit.
12. Practice Tasks
Task 1: Calculate a Total
Create a component that calculates the total of an array of numbers. Add an unrelated counter and compare how often the calculation runs before and after using useMemo.
Task 2: Search Students
Create a list of ten students and use useMemo to filter them by name. Verify that the filtered result changes when the search text changes.
Task 3: Sort Products
Create a product list with names and prices. Use useMemo to sort the products in ascending and descending order.
Task 4: Multiple Dependencies
Create a calculation that depends on two state values. Include both dependencies in useMemo and observe what happens when each value changes.
Task 5: Compare the Hooks
Explain the difference between useMemo, useState, and React.memo. Write one practical example for each.
Summary
The useMemo Hook caches the result of a calculation between renders while its dependencies remain unchanged. It is useful for expensive operations such as filtering student lists, sorting products, and calculating totals. Correct dependency arrays ensure that calculations update when relevant inputs change, while pure calculations keep rendering predictable. Unlike useState, useMemo does not store application state, and unlike React.memo, it memoizes a value rather than a component. At CIIT Training Institute, students should practise these examples and measure performance before deciding whether memoization provides a real benefit.