Vue Component Lifecycle: The unmounted Hook
The unmounted hook is the final stage in a Vue component's lifecycle. It's called right before a component instance is removed from the DOM and destroyed. It's your last chance to perform cleanup tasks.
When is unmounted called?
- When the component is removed from its parent component.
- When using
v-ifand the condition becomesfalse. - When using
<component :is="...">and the component being rendered changes. - When the parent component is destroyed.
- When using
v-forand the underlying data changes, causing the component to be removed from the list.
What can you do in unmounted?
This hook is crucial for preventing memory leaks and ensuring your application remains performant. Common use cases include:
- Removing Event Listeners: If you've manually added event listeners to
window,document, or other global objects within themountedhook, always remove them inunmounted. Failing to do so will cause memory leaks as the component is destroyed but the listeners remain active. - Cancelling Timers and Intervals: Clear any
setTimeoutorsetIntervaltimers you've set up. Otherwise, the timer callbacks will continue to execute even after the component is gone, leading to errors or unexpected behavior. - Cancelling HTTP Requests: If you have ongoing asynchronous operations (like fetching data with
fetchoraxios), cancel them to prevent updating a destroyed component's state. UseAbortControllerfor cleaner cancellation. - Releasing Resources: Release any resources held by the component, such as WebSockets connections, canvas contexts, or custom objects.
- Removing Global State Subscriptions: If your component subscribes to a global state management system (like Vuex or Pinia), unsubscribe to avoid unnecessary updates.
Example:
<template>
<div>
<button @click="startTimer">Start Timer</button>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: '',
timerId: null
};
},
mounted() {
this.startTimer();
},
methods: {
startTimer() {
this.timerId = setInterval(() => {
this.message = new Date().toLocaleTimeString();
}, 1000);
},
},
unmounted() {
clearInterval(this.timerId); // Clear the timer to prevent memory leaks
console.log('Component unmounted!');
}
};
</script>
Important Considerations:
- Don't access the DOM: The component is being removed from the DOM, so attempting to access it within
unmountedis unreliable and can lead to errors. - Avoid asynchronous operations: While technically possible, performing asynchronous operations in
unmountedis generally discouraged. The component is being destroyed, and any asynchronous results might not have a valid component instance to update. Cancel any ongoing operations beforeunmountedis called. unmountedvs.beforeUnmount: Vue 3 introducedbeforeUnmountwhich is called before the component's state is cleaned up.unmountedis called after cleanup. UsebeforeUnmountif you need to access the component's state before it's reset.
In summary, the unmounted hook is a vital part of the Vue component lifecycle. Using it correctly ensures your application is clean, efficient, and avoids common pitfalls like memory leaks.