Understanding <strong>useMemo</strong>
in React
The useMemo
hook in React is used to optimize performance by memoizing expensive computations. It prevents recalculating values unnecessarily by caching the result of a function when its dependencies donโt change.
Why <strong>useMemo</strong>
?
In React, re-rendering components can trigger unnecessary recalculations. useMemo
ensures that the computation happens only when needed (i.e., when specified dependencies change).
Custom Hook Example: <strong>useExpensiveCalculation</strong>
Hereโs a custom hook that demonstrates using useMemo
to optimize an expensive calculation.
Custom Hook Code:
import { useMemo } from "react";
const useExpensiveCalculation = (number) => {
const calculate = (num) => {
console.log("Running expensive calculation...");
let result = 0;
for (let i = 0; i <= 100000000; i++) {
result += num + i;
}
return result;
};
const result = useMemo(() => calculate(number), [number]);
return result;
};
export default useExpensiveCalculation;
How It Works:
<strong>useMemo</strong>
Cache:- The expensive
calculate
function runs only if <strong>number</strong>
changes. - If
number
remains the same, React uses the cached result.
Usage Example
Hereโs a component that uses the custom useExpensiveCalculation
hook:
import React, { useState } from "react";
import useExpensiveCalculation from "./useExpensiveCalculation";
const ExpensiveCalculationDemo = () => {
const [number, setNumber] = useState(1);
const [increment, setIncrement] = useState(0);
const result = useExpensiveCalculation(number);
return (
<div>
<h1>useMemo Hook Example</h1>
<p>Result of Expensive Calculation: {result}</p>
<button onClick={() => setNumber(number + 1)}>
Change Input (Number: {number})
</button>
{/* Increment unrelated to expensive calculation */}
<button onClick={() => setIncrement(increment + 1)}>
Increment Count: {increment}
</button>
</div>
);
};
export default ExpensiveCalculationDemo;
What Happens Here?
- The expensive calculation (
useExpensiveCalculation
) only runs when number
changes. - Clicking "Increment Count" triggers a re-render but does not recalculate the expensive value because
number
remains unchanged.
Key Notes About <strong>useMemo</strong>
:
- Syntax:
useMemo(() => computation, [dependencies])
- Only recomputes the value if the dependencies change.
- Ideal for expensive calculations or derived data.
This example demonstrates how useMemo
can optimize performance in functional components, making your React apps more efficient. Let us know if you'd like more details or use cases! ๐