<strong>useMemo</strong>
in ReactThe 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.
<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).
<strong>useExpensiveCalculation</strong>
Here’s a custom hook that demonstrates using useMemo
to optimize an expensive calculation.
import { useMemo } from "react";
// Custom Hook: Optimizes an expensive computation
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;
<strong>useMemo</strong>
Cache:calculate
function runs only if <strong>number</strong>
changes.number
remains the same, React uses the cached result.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;
useExpensiveCalculation
) only runs when number
changes.number
remains unchanged.<strong>useMemo</strong>
:useMemo(() => computation, [dependencies])
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! 🚀
Let's take a look at how we can speed up component rendering when performing expensive computations.
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.
Consider the calculateFibonacci function, which uses recursion to compute the Fibonacci sequence. This process is computationally very expensive.
When trying to increment the value of count, the UI is very sluggish as on each re-render, the sequence is recalculated.
The problem occurs on this line executing on each render.
Instead, we can use the useMemo hook, which will cache the result of the computation of the Fibonacci sequence. Similarly to useEffect hook, it has a dependency array that tells the useMemo when it needs to be re-computed.
Try clicking on the Increment Count button to see that the response is much faster! Clicking on Change Input re-calculates the Fibonacci sequence, be patient!