| useEffect vs useLayoutEffect :👈 | 👉:useCallback in React |
When Should You Use useMemo in React? |
When Should You Use useMemo in React?
1. Quick Answer
useMemo is a React Hook that caches the result of a calculation between renders. React recalculates the value when one of its dependencies changes.
Use useMemo when:
- A calculation is expensive and does not need to be repeated when its inputs have not changed.
- You need to preserve an object or array reference so that a memoized child component can avoid unnecessary rendering.
- You need a stable value for another Hook's dependency array and recreating that value would cause unnecessary work.
Rule of thumb: Write the simplest correct code first. Add useMemo when you identify a meaningful performance benefit. It is a performance optimization, not a requirement for every calculation.
2. Table of Contents
- Understanding useMemo
- Syntax and How It Works
- Use Case 1: Expensive Calculations
- Use Case 2: Filtering and Sorting Lists
- Use Case 3: Preserving Object and Array References
- Use Case 4: Hook Dependencies
- When You Do Not Need useMemo
- useMemo vs useCallback vs React.memo
- Common Mistakes
- Performance Considerations
- Best Practices
- Interview Questions
- Summary
3. Understanding useMemo
Every time a React component renders, its function runs again. Ordinary calculations inside that function are evaluated again unless their results are reused through an appropriate mechanism.
For example:
function ProductPage({ products, category }) {
const filteredProducts = products.filter(
product => product.category === category
);
return (
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
Whenever ProductPage renders, the filter calculation runs again, even if products and category have not changed.
For a small list, this is usually fine. For a very large list or a costly calculation, repeating the work may affect performance.
Using useMemo, you can cache the calculated result and reuse it while its dependencies remain unchanged.
4. Syntax and How It Works
Syntax
const memoizedValue = useMemo(() => {
return calculateValue();
}, [dependency1, dependency2]);
- Calculation function: Returns the value you want to cache.
- Dependencies: Values that the calculation reads and that determine when it must be recalculated.
- Returned value: The cached result from the previous render when the dependencies have not changed, or a newly calculated result when they have.
How It Works
React compares each dependency with its previous value using Object.is.
Important: React may discard a memoized value in certain situations. Therefore, useMemo should be treated as a performance optimization, not as a guarantee that a value will persist forever.
Basic Example
import { useMemo, useState } from "react";
function Example() {
const [count, setCount] = useState(0);
const [number, setNumber] = useState(10);
const doubled = useMemo(() => {
console.log("Calculating doubled value");
return number * 2;
}, [number]);
return (
<div>
<p>Count: {count}</p>
<p>Number: {number}</p>
<p>Doubled: {doubled}</p>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
<button onClick={() => setNumber(number + 1)}>
Increase Number
</button>
</div>
);
}
export default Example;
Clicking Increase Count causes the component to render again, but number has not changed, so React can reuse the memoized result.
Clicking Increase Number changes a dependency, so React recalculates doubled.
In development Strict Mode, React may call the calculation function more than once to help detect impure calculations. Do not use the console message as a precise measure of production execution frequency.
5. Use Case 1: Expensive Calculations
The most direct use case for useMemo is a calculation that takes significant time and depends on values that often remain unchanged.
Example: Calculating a Large Total
import { useMemo, useState } from "react";
function OrderSummary({ products }) {
const [count, setCount] = useState(0);
const total = useMemo(() => {
console.log("Calculating order total");
return products.reduce(
(sum, product) => sum + product.price * product.quantity,
0
);
}, [products]);
return (
<div>
<p>Order Total: ₹{total}</p>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
</div>
);
}
export default OrderSummary;
The total is recalculated when the products reference changes. A change to count alone does not require recalculating the total.
This is useful when calculating totals, statistics, aggregations, or other derived data from large datasets.
Note: The optimization helps only if the calculation is sufficiently expensive and the dependencies remain unchanged across renders. For a small array, a direct reduce may be simpler and just as effective overall.
6. Use Case 2: Filtering and Sorting Large Lists
Applications often filter and sort lists of products, users, orders, or search results.
Without useMemo
function ProductList({ products, searchTerm }) {
const filteredProducts = products
.filter(product =>
product.name.toLowerCase().includes(searchTerm.toLowerCase())
)
.sort((a, b) => a.name.localeCompare(b.name));
return (
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
The filtering and sorting operations run each time the component renders.
With useMemo
import { useMemo } from "react";
function ProductList({ products, searchTerm }) {
const filteredProducts = useMemo(() => {
const term = searchTerm.toLowerCase();
return products
.filter(product =>
product.name.toLowerCase().includes(term)
)
.sort((a, b) => a.name.localeCompare(b.name));
}, [products, searchTerm]);
return (
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
export default ProductList;
Now React can reuse the filtered and sorted array when both products and searchTerm remain unchanged.
Why Include Both Dependencies?
productsdetermines which items are available.searchTermdetermines which items match.
If either value changes, the calculation must run again to produce correct results.
Important: sort() modifies the array on which it is called. In this example, filter() creates a new array first, so the original products array is not sorted in place. If sorting an existing array directly, copy it first or use a non-mutating alternative such as toSorted() where supported.
7. Use Case 3: Preserving Object and Array References
JavaScript creates a new reference when you create an object or array. React's memoization tools can compare references to determine whether a value has changed.
This matters when passing objects or arrays to a child component wrapped in React.memo.
Example Without useMemo
import { memo, useState } from "react";
const UserDetails = memo(function UserDetails({ user }) {
console.log("UserDetails rendered");
return <p>Name: {user.name}</p>;
});
function Parent() {
const [count, setCount] = useState(0);
const user = {
name: "Sam"
};
return (
<div>
<UserDetails user={user} />
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
</div>
);
}
export default Parent;
Whenever Parent renders, it creates a new user object. Although the name is unchanged, the object reference is different. Consequently, React.memo sees a changed prop and the child renders again.
Example With useMemo
import { memo, useMemo, useState } from "react";
const UserDetails = memo(function UserDetails({ user }) {
console.log("UserDetails rendered");
return <p>Name: {user.name}</p>;
});
function Parent() {
const [count, setCount] = useState(0);
const user = useMemo(() => ({
name: "Sam"
}), []);
return (
<div>
<UserDetails user={user} />
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
</div>
);
}
export default Parent;
Because the memoized object reference can be reused across renders, React.memo can skip rendering UserDetails when its other props have not changed.
In this example, the object is static, so another simple option is to define it outside the component. Use useMemo when the value depends on component props or state or when keeping it within the component is useful.
8. Use Case 4: Hook Dependencies
An object created during rendering can cause an effect to run more often than necessary if it is included in that effect's dependency array.
Problem: Object Created on Every Render
import { useEffect, useState } from "react";
function SearchResults({ query }) {
const [results, setResults] = useState([]);
const options = {
query,
limit: 10
};
useEffect(() => {
// Example placeholder for a search operation.
console.log("Search options changed:", options);
}, [options]);
return <p>Results: {results.length}</p>;
}
The options object is recreated on every render. Its reference therefore changes, causing the effect to run again even when query has not changed.
Solution 1: Create the Object Inside the Effect
useEffect(() => {
const options = {
query,
limit: 10
};
// Use options to synchronize with the external system.
}, [query]);
This is often the simplest solution because the effect depends directly on the primitive value it needs.
Solution 2: Use useMemo
const options = useMemo(() => ({
query,
limit: 10
}), [query]);
useEffect(() => {
// Use options to synchronize with the external system.
}, [options]);
This keeps the object reference stable while query remains unchanged. However, prefer the first approach when creating the object inside the effect makes the dependency logic simpler.
9. When You Do Not Need useMemo
Case 1: Simple Calculations
For inexpensive calculations, memoization may add complexity without providing a meaningful benefit.
Usually unnecessary:
const doubled = useMemo(() => number * 2, [number]);
Simpler:
const doubled = number * 2;
Case 2: A Value Is Only Used Once
If a value is cheap to calculate and does not need a stable reference, a normal variable is usually sufficient.
const fullName = `${firstName} ${lastName}`;
Case 3: You Are Trying to Prevent Every Render
useMemo does not stop a component from rendering. It only caches the result of a calculation. To skip rendering a child when its props are unchanged, React.memo may help if its requirements are met.
Case 4: You Need Guaranteed Persistence
Do not use useMemo to guarantee that an object persists for the entire lifetime of a component. React treats memoization as an optimization and may discard cached values in specific situations.
If you need to store a mutable value that does not trigger rendering, consider useRef. If you need state that triggers rendering, use a state hook.
10. useMemo vs useCallback vs React.memo
| Feature | useMemo | useCallback | React.memo |
|---|---|---|---|
| Type | Hook | Hook | Component memoization function |
| Primary purpose | Cache a calculated value. | Cache a function reference. | Skip rendering a component when its props are unchanged, subject to React's behavior. |
| Returns | The calculated value. | The function. | A memoized component. |
| Typical use | Expensive calculations and stable object or array references. | Stable callbacks passed to memoized children or used as dependencies. | Expensive child components that often receive unchanged props. |
Example: useCallback
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
useCallback caches the function reference. By comparison, useMemo caches the result returned by a calculation.
Example: React.memo
const Child = memo(function Child({ name }) {
return <p>{name}</p>;
});
React.memo can skip rendering the child when its props remain unchanged according to its comparison behavior. It does not prevent the child from rendering when its own state or consumed context changes.
11. Common Mistakes
Mistake 1: Missing Dependencies
const total = useMemo(() => {
return price * quantity;
}, [price]);
The calculation also uses quantity, so the dependency array is incomplete.
Correct:
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
Mistake 2: Mutating an Existing Array
const sortedProducts = useMemo(() => {
return products.sort((a, b) => a.price - b.price);
}, [products]);
This mutates the original products array. Memoization does not make mutation safe.
Correct:
const sortedProducts = useMemo(() => {
return [...products].sort(
(a, b) => a.price - b.price
);
}, [products]);
Mistake 3: Expecting useMemo to Prevent Component Renders
The component still renders when its state or props change. useMemo can skip a calculation when dependencies are unchanged, but it does not prevent the component itself from rendering.
Mistake 4: Using useMemo for Every Variable
Memoizing every calculation makes code harder to read and maintain. Use it when the calculation is expensive or when stable identity provides a concrete benefit.
Mistake 5: Using an Unstable Dependency
const options = { limit: 10 };
const result = useMemo(() => {
return calculateResult(options);
}, [options]);
Because options is a new object on every render, the calculation runs again every time. Consider creating the object inside the memoized calculation or using primitive dependencies.
Mistake 6: Using useMemo for Side Effects
useMemo is intended for pure calculations, not API calls, subscriptions, timers, or other side effects.
Use an effect or event handler for side effects. Keep the memoized calculation pure and predictable.
12. Performance Considerations
- Measure first: Use React DevTools Profiler or browser performance tools to find expensive calculations and unnecessary rendering.
- Focus on meaningful work: Filtering thousands of records may benefit from memoization more than multiplying two numbers.
- Check dependency stability: If a dependency is recreated on every render, memoization may not provide the expected benefit.
- Consider memory usage: Cached values consume memory for as long as React retains them.
- Keep code understandable: A direct calculation may be preferable when its cost is negligible.
- Remember development behavior: Strict Mode may run calculations more than once in development to help identify impure code.
In many applications, improving the algorithm, reducing unnecessary state updates, or rendering fewer list items has a greater impact than adding useMemo everywhere.
13. Best Practices
- Use
useMemofor expensive calculations whose dependencies often remain unchanged. - Use it to preserve object or array references when a consumer benefits from stable identity.
- Include every reactive value used by the calculation in the dependency array.
- Keep the calculation pure and avoid modifying existing state or props.
- Prefer primitive dependencies when practical.
- Do not use it as a replacement for state, refs, or effects.
- Do not assume that memoization guarantees a value will persist forever.
- Use React DevTools Profiler to confirm that the optimization is worthwhile.
- Consider whether a better algorithm or simpler component structure would solve the problem more effectively.
14. Interview Questions
Q1. What is useMemo in React?
Answer: useMemo is a Hook that caches the result of a calculation between renders and recalculates it when its dependencies change.
Q2. When should you use useMemo?
Answer: Use it when an expensive calculation can be reused or when a stable object or array reference helps avoid unnecessary work.
Q3. Does useMemo prevent component re-rendering?
Answer: No. It caches a calculated value. React.memo can help skip rendering a child when its props are unchanged.
Q4. What happens when a dependency changes?
Answer: React recalculates the memoized value during rendering.
Q5. What is the difference between useMemo and useCallback?
Answer: useMemo caches a calculation's result, while useCallback caches a function reference.
Q6. Can useMemo be used for API calls?
Answer: No. API calls are side effects. Use an effect or an event handler, or use an appropriate data-fetching library.
Q7. Does useMemo guarantee that the value will never be recalculated?
Answer: No. React may discard the cached value in specific situations. It is a performance optimization, not a persistence guarantee.
Q8. Should every calculation use useMemo?
Answer: No. Simple calculations are usually better written directly. Memoize when the performance benefit justifies the added complexity.
15. Summary
| Situation | Use useMemo? | Reason |
|---|---|---|
| Simple arithmetic | Usually no | The calculation is inexpensive. |
| Filtering a very large list | Potentially yes | Avoid repeating expensive work when inputs are unchanged. |
| Sorting a large dataset | Potentially yes | Reuse the sorted result until its dependencies change. |
| Object passed to a memoized child | Potentially yes | Preserve the object reference when its inputs are unchanged. |
| Function passed to a memoized child | Use useCallback when appropriate | Preserve the function reference. |
| Preventing a child from rendering | Not by itself | Consider React.memo and stable props. |
| API request or subscription | No | Use an effect, event handler, or data-fetching solution. |
Final recommendation: Use useMemo when it avoids a meaningful amount of repeated work or helps maintain stable references. Do not add it automatically to every variable. Write clear code first, measure performance, and optimize where it matters.
| useEffect vs useLayoutEffect :👈 | 👉:useCallback in React |
Comments and Discussion