JAVASCRIPT
Optimize Expensive Calculations with useMemo
Boost React app performance by memoizing the result of computationally intensive functions using the `useMemo` hook, preventing unnecessary re-calculations on re-renders.
import React, { useState, useMemo } from 'react';
// A simulated expensive calculation function
const calculateExpensiveValue = (count) => {
console.log('Calculating expensive value...');
// Simulate heavy computation
let sum = 0;
for (let i = 0; i < count * 1000000; i++) {
sum += i;
}
return sum;
};
function ExpensiveCalculationComponent() {
const [count, setCount] = useState(1);
const [inputValue, setInputValue] = useState('');
// Use useMemo to memoize the result of calculateExpensiveValue
// It will only re-run if 'count' changes.
const memoizedValue = useMemo(() => {
return calculateExpensiveValue(count);
}, [count]); // Dependency array: re-calculate only if 'count' changes
return (
<div>
<h2>useMemo Example</h2>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<p>Expensive Calculation Result: {memoizedValue}</p>
<hr />
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Type here (won't re-calculate)"
/>
<p>Input Value: {inputValue}</p>
</div>
);
}
export default ExpensiveCalculationComponent;
How it works: This snippet demonstrates `useMemo` for optimizing performance by memoizing the result of an expensive calculation. The `calculateExpensiveValue` function simulates a computationally intensive operation. By wrapping its call in `useMemo`, the `memoizedValue` is only re-calculated when its dependencies (in this case, `count`) change. This prevents the expensive computation from re-running on every render triggered by unrelated state changes, like updating the `inputValue`.