useMemo Hook
Learn how to use the useMemo Hook to cache calculated values between renders and avoid unnecessary recalculation when the relevant dependencies have not changed.
1. What Is the useMemo Hook?
The useMemo Hook is a built-in React Hook that caches the result of a calculation between renders. React recalculates the value when one of its dependencies changes.
It can be useful when a component performs an expensive calculation and the inputs to that calculation often remain unchanged between renders.
2. Syntax of useMemo
The basic syntax is:
const cachedValue = useMemo(() => {
return calculateValue();
}, [dependencies]);
- Calculation function: Returns the value that React should cache.
- Dependencies: Values used by the calculation that determine when it needs to run again.
- cachedValue: The result returned by the calculation function.
3. How useMemo Works
React calculates the value when needed and can reuse the cached result on later renders while the dependencies remain unchanged.
4. Example: Calculating a Total
In this example, useMemo calculates the total price from a quantity and price. The total is recalculated when either dependency changes.
Example Code
import { useMemo, useState } from "react";
function App() {
const [quantity, setQuantity] = useState(2);
const price = 100;
const total = useMemo(() => {
return quantity * price;
}, [quantity, price]);
return (
<div>
<h2>Price Calculator</h2>
<p>Price: ₹{price}</p>
<p>Quantity: {quantity}</p>
<p>Total: ₹{total}</p>
<button onClick={() =>
setQuantity(quantity + 1)
}>
Increase Quantity
</button>
</div>
);
}
export default App;
Expected Output
Price Calculator
Price: ₹100
Quantity: 2
Total: ₹200
After clicking Increase Quantity once:
Quantity: 3
Total: ₹3005. Example: Caching an Expensive Calculation
useMemo is useful when a calculation takes significant time and does not need to be repeated when its inputs remain unchanged.
Example Code
import { useMemo, useState } from "react";
function calculateTotal(number) {
console.log("Calculating total...");
let total = 0;
for (let i = 1; i <= number; i++) {
total += i;
}
return total;
}
function App() {
const [number, setNumber] = useState(100);
const [theme, setTheme] = useState("light");
const total = useMemo(() => {
return calculateTotal(number);
}, [number]);
return (
<div>
<h2>Calculation Example</h2>
<p>Number: {number}</p>
<p>Total: {total}</p>
<button onClick={() =>
setNumber(number + 1)
}>
Increase Number
</button>
<button onClick={() =>
setTheme(theme === "light"
? "dark"
: "light")
}>
Change Theme
</button>
<p>Theme: {theme}</p>
</div>
);
}
export default App;
Expected Output
Number: 100
Total: 5050
After clicking Change Theme:
Theme: dark
The calculation does not need to run again just because the theme changes, since number remains unchanged.
After clicking Increase Number:
Number: 101
Total: 51516. Important Points About useMemo
- Import useMemo from React.
- Call Hooks at the top level of a component or custom Hook.
- Include every reactive value used by the calculation in the dependency array.
- Keep the calculation pure and free of side effects.
- useMemo caches a calculated value, not a function.
- Do not use useMemo automatically for every calculation. Use it when memoization provides a meaningful benefit.
- React may discard cached values in certain situations, so the cache must not be required for correctness.
7. Difference Between useMemo and useCallback
- useMemo: Caches the result of a calculation.
- useCallback: Caches a function definition between renders.
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
8. Practice Tasks
Complete the following exercises:
- Create a price calculator using useMemo.
- Calculate the total marks of a student using useMemo.
- Create a list and calculate its total without repeating the calculation when unrelated state changes.
- Create a component with number and theme state variables. Cache a calculation that depends only on number.
- Explain the difference between useMemo and useCallback.