Intermediate LevelVue JS
How do you prevent memory leaks from event listeners and intervals inside Vue Composables?
❓ Interview Prompt: Explain lifecycle linkage inside composables, automatically cleaning up event listeners, and onUnmounted scope binding.
When writing composables that register global event listeners ('window.addEventListener'), WebSockets, or timers ('setInterval'), failing to clean up resources when the host component unmounts creates severe memory leaks.
Automatic Lifecycle Linkage:
If 'onUnmounted()' is called inside a composable during component setup, Vue automatically attaches the unmount hook to the lifecycle of whichever component invokes the composable!
Code Implementation Example
javascript
// composables/useWindowSize.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useWindowSize() {
const width = ref(window.innerWidth);
const update = () => width.value = window.innerWidth;
onMounted(() => window.addEventListener('resize', update));
// Automatically cleans up resize listener when host component unmounts!
onUnmounted(() => window.removeEventListener('resize', update));
return { width };
}💡Preventing memory leaks by binding listener cleanup to onUnmounted inside composables.
🎯 Interview Key Takeaway
Always clean up event listeners and timers inside onUnmounted() when building reusable Vue composables.
#Composables#Memory Leaks#onUnmounted#Intermediate
Back to all Vue JS Questions→