0
0
Reactframework~8 mins

Cleanup function in React - Performance & Optimization

Choose your learning style9 modes available
Performance: Cleanup function
MEDIUM IMPACT
This affects interaction responsiveness and memory usage by properly cleaning up side effects in React components.
Managing subscriptions or timers inside React useEffect
React
useEffect(() => {
  const id = setInterval(() => {
    console.log('tick');
  }, 1000);
  return () => clearInterval(id);
}, []);
Cleanup stops the interval when the component unmounts, freeing resources and improving responsiveness.
📈 Performance GainPrevents memory leaks and unnecessary CPU use, improving INP and overall app performance.
Managing subscriptions or timers inside React useEffect
React
useEffect(() => {
  const id = setInterval(() => {
    console.log('tick');
  }, 1000);
  // No cleanup function
}, []);
Without cleanup, intervals keep running even after component unmounts, causing memory leaks and wasted CPU.
📉 Performance CostCauses memory leaks and continuous CPU usage, increasing INP and slowing user interactions.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Effect without cleanupNo extra DOM nodesNo reflowsNo paint cost[X] Bad - causes memory leaks and CPU waste
Effect with cleanupNo extra DOM nodesNo reflowsNo paint cost[OK] Good - frees resources and improves responsiveness
Rendering Pipeline
React effects run after rendering. Cleanup functions run before the next effect or on unmount to remove side effects, preventing extra work and memory use.
Commit phase
Effect cleanup
JavaScript execution
⚠️ BottleneckJavaScript execution during effect cleanup if missing or inefficient
Core Web Vital Affected
INP
This affects interaction responsiveness and memory usage by properly cleaning up side effects in React components.
Optimization Tips
1Always return a cleanup function from useEffect to clear timers, subscriptions, or event listeners.
2Cleanup functions run before the next effect or on unmount to prevent memory leaks.
3Proper cleanup improves interaction responsiveness and reduces CPU waste.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using a cleanup function in React's useEffect?
AIt speeds up the initial render of the component.
BIt reduces the size of the JavaScript bundle.
CIt prevents memory leaks and reduces CPU usage after component unmount.
DIt improves CSS selector matching speed.
DevTools: Performance
How to check: Record a session while mounting and unmounting the component. Look for long tasks or continuous CPU usage after unmount.
What to look for: If CPU usage continues or memory grows after unmount, cleanup is missing or inefficient.