JAVASCRIPT
React useMemo for Memoizing Expensive Calculations
Optimize your React functional components with the useMemo hook to prevent re-running expensive calculations on every render, enhancing performance.
import React, { useState, useMemo } from 'react';
function calculateExpensiveValue(num) {
console.log('Calculating expensive value...');
// Simulate an expensive calculation
let result = 0;
for (let i = 0; i < 100000000; i++) {
result += i;
}
return result + num;
}
function MemoizedCounter() {
const [count, setCount] = useState(0);
const [multiplier, setMultiplier] = useState(1);
// Only re-run calculateExpensiveValue when 'multiplier' changes
const memoizedValue = useMemo(() => {
return calculateExpensiveValue(multiplier);
}, [multiplier]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<p>Multiplier: {multiplier}</p>
<button onClick={() => setMultiplier(multiplier + 1)}>Increment Multiplier</button>
<p>Expensive Calculation Result: {memoizedValue}</p>
</div>
);
}
export default MemoizedCounter;
How it works: The `useMemo` hook is a performance optimization tool in React that memoizes the result of an expensive calculation. It takes two arguments: a function that computes a value, and a dependency array. React will only re-run the computation function if one of the dependencies in the array has changed since the last render. In this example, `calculateExpensiveValue` is a simulated expensive function. `memoizedValue` is only re-calculated when `multiplier` changes, preventing the expensive operation from running unnecessarily when only `count` is updated, thereby improving component render performance.