How to Use onUnmounted in Vue

The onUnmounted lifecycle hook in Vue 3 Composition API is essential for cleaning up resources when components are destroyed to prevent memory leaks and ensure optimal performance. As the creator of CoreUI with over 11 years of Vue.js development experience, I implement onUnmounted in every component that creates timers, event listeners, or external subscriptions. This hook is called when the component is unmounted from the DOM, making it perfect for cleanup operations.

Use onUnmounted in the setup function to clean up resources like timers, event listeners, and subscriptions before component destruction.

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

export default {
  setup() {
    const data = ref([])
    const count = ref(0)
    let intervalId = null
    let websocket = null

    onMounted(() => {
      // Set up timer
      intervalId = setInterval(() => {
        count.value++
      }, 1000)

      // Set up WebSocket connection
      websocket = new WebSocket('ws://localhost:8080')
      websocket.onmessage = (event) => {
        data.value.push(JSON.parse(event.data))
      }

      // Add global event listener
      window.addEventListener('resize', handleResize)
      document.addEventListener('keydown', handleKeydown)
    })

    onUnmounted(() => {
      // Clear timers
      if (intervalId) {
        clearInterval(intervalId)
        intervalId = null
      }

      // Close WebSocket connection
      if (websocket) {
        websocket.close()
        websocket = null
      }

      // Remove global event listeners
      window.removeEventListener('resize', handleResize)
      document.removeEventListener('keydown', handleKeydown)

      console.log('Component cleanup completed')
    })

    const handleResize = () => {
      console.log('Window resized')
    }

    const handleKeydown = (event) => {
      if (event.key === 'Escape') {
        console.log('Escape key pressed')
      }
    }

    return {
      data,
      count
    }
  },
  template: `
    <div>
      <p>Count: {{ count }}</p>
      <div v-for="item in data" :key="item.id">
        {{ item.message }}
      </div>
    </div>
  `
}

The onUnmounted hook is called automatically when Vue removes the component from the DOM. Always clear timers created with setInterval or setTimeout to prevent them from continuing to run after component destruction. Remove global event listeners added to window, document, or other DOM elements. Close WebSocket connections, cancel ongoing HTTP requests, and clean up any external resources. This cleanup prevents memory leaks and ensures optimal application performance.

Best Practice Note:

In CoreUI components, we consistently implement onUnmounted for proper resource management, especially for components with real-time features, data polling, or global event handling. This practice ensures our Vue.js components remain performant and memory-efficient even in complex single-page applications with frequent component mounting and unmounting.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Redirect to a New URL Using JavaScript Redirect Techniques
How to Redirect to a New URL Using JavaScript Redirect Techniques

What is globalThis in JavaScript?
What is globalThis in JavaScript?

What Does javascript:void(0) Mean?
What Does javascript:void(0) Mean?

How to Merge Objects in JavaScript
How to Merge Objects in JavaScript

Answers by CoreUI Core Team