Module: Vue Component Lifecycle

Unmounted hook

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-if and the condition becomes false.
  • When using <component :is="..."> and the component being rendered changes.
  • When the parent component is destroyed.
  • When using v-for and 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 the mounted hook, always remove them in unmounted. Failing to do so will cause memory leaks as the component is destroyed but the listeners remain active.
  • Cancelling Timers and Intervals: Clear any setTimeout or setInterval timers 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 fetch or axios), cancel them to prevent updating a destroyed component's state. Use AbortController for 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 unmounted is unreliable and can lead to errors.
  • Avoid asynchronous operations: While technically possible, performing asynchronous operations in unmounted is generally discouraged. The component is being destroyed, and any asynchronous results might not have a valid component instance to update. Cancel any ongoing operations before unmounted is called.
  • unmounted vs. beforeUnmount: Vue 3 introduced beforeUnmount which is called before the component's state is cleaned up. unmounted is called after cleanup. Use beforeUnmount if 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.