0 day streak
javascript / intermediate
Snippet

Optimizing Performance with useMemo

useMemo caches the result of a calculation between re-renders, only recalculating when one of its dependencies changes, saving CPU cycles.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const expensiveCalculation = (num: number) => {
console.log('Calculating...');
for (let i = 0; i < 1000000000; i++) {} // Simulate load
return num * 2;
};
function Dashboard({ count }: { count: number }) {
const memoizedValue = useMemo(() => expensiveCalculation(count), [count]);
return <div>Result: {memoizedValue}</div>;
}
nextjs
Breakdown
1
useMemo(() => ..., [count])
Executes the function only when 'count' changes.
2
expensiveCalculation(count)
A placeholder for any logic that is computationally heavy.