0
0
VueConceptBeginner · 3 min read

What is onUnmounted in Vue: Usage and Examples

onUnmounted is a Vue Composition API lifecycle hook that runs a function when a component is removed from the DOM. It helps you clean up resources like timers or event listeners to avoid memory leaks.
⚙️

How It Works

Imagine you have a room where you set up some decorations and lights. When you leave the room, you want to turn off the lights and remove the decorations to keep things tidy. onUnmounted works like that for Vue components. It lets you run cleanup code right when the component is about to be removed from the page.

When a Vue component is created, it can set up things like timers, event listeners, or subscriptions. If these are not stopped or removed when the component disappears, they can keep running and cause problems. onUnmounted lets you tell Vue exactly what to do to clean up, so your app stays fast and bug-free.

💻

Example

This example shows a timer that counts seconds while the component is visible. When the component is removed, the timer stops using onUnmounted.

vue
import { ref, onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    const seconds = ref(0);
    let timer = null;

    onMounted(() => {
      timer = setInterval(() => {
        seconds.value++;
      }, 1000);
    });

    onUnmounted(() => {
      clearInterval(timer);
      console.log('Timer stopped');
    });

    return { seconds };
  },
  template: `<div>Seconds: {{ seconds }}</div>`
};
Output
Seconds: 0 (then increments every second until component unmounts, then stops and logs 'Timer stopped')
🎯

When to Use

Use onUnmounted whenever your component sets up something that needs to be cleaned up later. This includes:

  • Stopping timers or intervals
  • Removing event listeners added to the window or document
  • Canceling network requests or subscriptions
  • Cleaning up third-party libraries or plugins

This helps prevent memory leaks and unexpected behavior when components come and go in your app.

Key Points

  • onUnmounted runs cleanup code when a component is removed.
  • It is part of Vue's Composition API lifecycle hooks.
  • Use it to stop timers, remove listeners, or cancel subscriptions.
  • Helps keep your app efficient and bug-free.

Key Takeaways

onUnmounted runs code when a Vue component is removed from the DOM.
Use it to clean up timers, event listeners, and other resources.
It prevents memory leaks and keeps your app running smoothly.
onUnmounted is part of Vue's Composition API lifecycle hooks.