0
0
Vueframework~8 mins

Effective scope for cleanup in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Effective scope for cleanup
MEDIUM IMPACT
This concept affects how efficiently Vue components release resources and avoid memory leaks, impacting long-term page responsiveness and stability.
Cleaning up event listeners or timers in Vue components
Vue
import { onMounted, onUnmounted } from 'vue';
onMounted(() => {
  window.addEventListener('resize', onResize);
});
onUnmounted(() => {
  window.removeEventListener('resize', onResize);
});
Removes event listener exactly when component unmounts, freeing memory and stopping unnecessary work.
📈 Performance GainPrevents memory leaks and reduces CPU usage, improving interaction responsiveness.
Cleaning up event listeners or timers in Vue components
Vue
import { onMounted } from 'vue';
onMounted(() => {
  window.addEventListener('resize', onResize);
});
// No cleanup on unmount
Event listener stays active after component unmount, causing memory leaks and unnecessary event handling.
📉 Performance CostCauses memory leaks and extra CPU usage on every resize event even when component is gone.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No cleanup of event listenersNo direct DOM ops00[X] Bad
Cleanup in onUnmounted hookNo direct DOM ops00[OK] Good
Rendering Pipeline
Cleanup code runs during component unmount lifecycle, preventing unnecessary DOM updates and event handling after removal.
JavaScript Execution
Event Handling
⚠️ BottleneckExcess event listeners or timers causing unnecessary JavaScript execution
Core Web Vital Affected
INP
This concept affects how efficiently Vue components release resources and avoid memory leaks, impacting long-term page responsiveness and stability.
Optimization Tips
1Always pair resource setup with cleanup in the same component scope.
2Use onUnmounted to remove event listeners and timers.
3Avoid global side effects that persist beyond component lifecycle.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is it important to clean up event listeners in Vue components?
ATo prevent memory leaks and reduce unnecessary CPU usage
BTo make the component load faster initially
CTo improve CSS rendering speed
DTo reduce the size of the JavaScript bundle
DevTools: Performance
How to check: Record a session while mounting and unmounting the component multiple times; look for increasing memory or event handler counts.
What to look for: Memory usage should stay stable and event listeners count should not grow after repeated mounts/unmounts.