JAVASCRIPT
Memoize Expensive Calculations with useMemo for Performance Optimization
Discover how `useMemo` in React can prevent re-running computationally expensive functions on every render by memoizing their return values based on dependencies.
import React, { useState, useMemo } from 'react';
function calculateExpensiveValue(num) {
console.log('Calculating expensive value...');
// Simulate an expensive calculation
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
return num * 2 + sum;
}
function MemoExample() {
const [count, setCount] = useState(0);
const [anotherState, setAnotherState] = useState(0);
// The expensive calculation will only re-run if 'count' changes
const memoizedValue = useMemo(() => {
return calculateExpensiveValue(count);
}, [count]); // Dependency array: re-run only when 'count' changes
return (
<div>
<p>Count: {count}</p>
<p>Expensive Value: {memoizedValue}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<hr />
<p>Another State: {anotherState}</p>
<button onClick={() => setAnotherState(anotherState + 1)}>Increment Another State</button>
<p>Notice: "Calculating expensive value..." only logs when Count changes, not Another State.</p>
</div>
);
}
export default MemoExample;
How it works: The `useMemo` hook is used to memoize the result of `calculateExpensiveValue(count)`. This means the `calculateExpensiveValue` function will only execute when `count` (its dependency) changes. If `anotherState` updates and causes a re-render of `MemoExample`, `calculateExpensiveValue` will *not* be re-run, because `count` has not changed, thus optimizing performance by skipping unnecessary computations.