0
0
Vueframework~8 mins

Composable with lifecycle hooks in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Composable with lifecycle hooks
MEDIUM IMPACT
This affects how efficiently Vue components manage side effects and resource cleanup during rendering and interaction.
Managing side effects and cleanup in Vue components using composables
Vue
import { onMounted, onUnmounted } from 'vue';

export function useTimer() {
  let intervalId = null;
  onMounted(() => {
    intervalId = setInterval(() => {
      console.log('tick');
    }, 1000);
  });
  onUnmounted(() => {
    clearInterval(intervalId);
  });
}
Properly clears the interval when the component unmounts, freeing resources and avoiding unnecessary work.
📈 Performance GainPrevents memory leaks and reduces CPU usage, improving interaction responsiveness.
Managing side effects and cleanup in Vue components using composables
Vue
import { onMounted, onUnmounted } from 'vue';

export function useTimer() {
  let intervalId = null;
  onMounted(() => {
    intervalId = setInterval(() => {
      console.log('tick');
    }, 1000);
  });
  // Missing cleanup on unmount
}
Not cleaning up the interval on component unmount causes memory leaks and unnecessary CPU usage.
📉 Performance CostCauses continuous background work, increasing CPU usage and reducing responsiveness.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Composable without cleanupMinimal0Low but ongoing CPU usage[X] Bad
Composable with proper lifecycle cleanupMinimal0Low and stops when unused[OK] Good
Rendering Pipeline
Lifecycle hooks in composables run during component setup and teardown, affecting when side effects start and stop in the rendering process.
Setup
Cleanup
Reactive Updates
⚠️ BottleneckUnmanaged side effects causing background work after component unmount
Core Web Vital Affected
INP
This affects how efficiently Vue components manage side effects and resource cleanup during rendering and interaction.
Optimization Tips
1Always pair side effects with cleanup in lifecycle hooks to avoid leaks.
2Use onMounted and onUnmounted to start and stop timers or subscriptions.
3Proper lifecycle management improves interaction responsiveness (INP).
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of not using onUnmounted in a composable with side effects?
AIncreased DOM nodes
BMemory leaks and unnecessary CPU usage
CSlower initial page load
DLonger CSS calculation times
DevTools: Performance
How to check: Record a session while mounting and unmounting the component using the composable. Look for ongoing CPU activity after unmount.
What to look for: CPU usage spikes or continuous timers running after component unmount indicate missing cleanup.