0
0
Reactframework~8 mins

useMemo hook in React - Performance & Optimization

Choose your learning style9 modes available
Performance: useMemo hook
MEDIUM IMPACT
This affects the rendering speed and responsiveness by avoiding unnecessary recalculations during component renders.
Optimizing expensive calculations inside a React functional component
React
import { useMemo } from 'react';
function Component({items}) {
  const total = useMemo(() => items.reduce((sum, item) => sum + item.value, 0), [items]);
  return <div>Total: {total}</div>;
}
Calculation runs only when items change, reducing CPU load and speeding up renders.
📈 Performance GainReduces CPU work and improves INP by avoiding redundant recalculations
Optimizing expensive calculations inside a React functional component
React
function Component({items}) {
  const total = items.reduce((sum, item) => sum + item.value, 0);
  return <div>Total: {total}</div>;
}
The calculation runs on every render even if items haven't changed, causing unnecessary CPU work and slower interaction.
📉 Performance CostBlocks rendering for each render, increasing INP and CPU usage
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Without useMemoNo changeMultiple reflows if calculation triggers state changesHigher paint cost due to slower JS[X] Bad
With useMemoNo changeSingle reflow if dependencies changeLower paint cost due to cached results[OK] Good
Rendering Pipeline
useMemo caches the result of a calculation between renders, so React skips recalculating the value if dependencies haven't changed.
JavaScript Execution
⚠️ BottleneckJavaScript Execution when recalculations are expensive
Core Web Vital Affected
INP
This affects the rendering speed and responsiveness by avoiding unnecessary recalculations during component renders.
Optimization Tips
1Use useMemo to cache expensive calculations that depend on specific inputs.
2Avoid useMemo for cheap or simple calculations to prevent unnecessary overhead.
3Always include all dependencies in the useMemo dependency array to avoid stale values.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using useMemo in React?
AIt caches expensive calculations to avoid repeating them on every render.
BIt delays rendering until the user interacts with the component.
CIt reduces the size of the JavaScript bundle.
DIt automatically batches multiple state updates.
DevTools: Performance
How to check: Record a performance profile while interacting with the component. Look for long scripting tasks caused by recalculations.
What to look for: Reduced scripting time and fewer recalculations when props/state do not change indicate good useMemo usage.