0
0
Vueframework~8 mins

onMounted and onUnmounted in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: onMounted and onUnmounted
MEDIUM IMPACT
These lifecycle hooks affect the timing of DOM interactions and resource cleanup, impacting rendering responsiveness and memory usage.
Managing event listeners in a Vue component
Vue
import { onMounted, onUnmounted } from 'vue';
onMounted(() => {
  window.addEventListener('resize', onResize);
});
onUnmounted(() => {
  window.removeEventListener('resize', onResize);
});
Removes event listener when component unmounts, freeing memory and avoiding unnecessary event handling.
📈 Performance GainReduces memory leaks and improves interaction responsiveness by cleaning up listeners.
Managing event listeners in a Vue component
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 CostIncreases memory usage and causes unnecessary event processing, leading to slower input responsiveness.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Add event listener in onMounted only1 addEventListener0 reflows0 paint[X] Bad
Add in onMounted and remove in onUnmounted1 addEventListener + 1 removeEventListener0 reflows0 paint[OK] Good
Rendering Pipeline
onMounted runs after the component's DOM is inserted, allowing safe DOM reads and writes without blocking initial paint. onUnmounted runs before the component is removed, enabling cleanup to prevent memory leaks and extra work.
DOM Insertion
Layout
Paint
Memory Management
⚠️ BottleneckMemory Management due to leftover event listeners or timers if cleanup is missing
Core Web Vital Affected
INP
These lifecycle hooks affect the timing of DOM interactions and resource cleanup, impacting rendering responsiveness and memory usage.
Optimization Tips
1Always add event listeners or timers in onMounted.
2Always remove event listeners or timers in onUnmounted.
3Cleaning up prevents memory leaks and improves input responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of adding event listeners only in onMounted without removing them in onUnmounted?
AMemory leaks and slower input responsiveness
BSlower initial page load
CIncreased CSS paint cost
DDelayed DOM insertion
DevTools: Performance
How to check: Record a session while mounting and unmounting the component. Look for event listeners and memory usage in the summary and flame chart.
What to look for: Check if event listeners persist after unmount and if memory usage drops after cleanup, indicating good performance.