How to use onBeforeUnmount in Vue

Performing cleanup tasks before a component is unmounted is crucial for preventing memory leaks and ensuring proper resource management in Vue applications. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development including Vue.js since 2014, I’ve implemented countless components that require cleanup of timers, subscriptions, and event listeners. The most effective approach is using the onBeforeUnmount lifecycle hook in Vue 3’s Composition API, which provides the perfect timing for cleanup operations. This hook is essential for maintaining application performance and preventing memory leaks in long-running applications.

Use onBeforeUnmount in the Composition API to perform cleanup tasks before the component is destroyed.

import { onBeforeUnmount, onMounted } from 'vue'

export default {
  setup() {
    let intervalId

    onMounted(() => {
      intervalId = setInterval(() => {
        console.log('Timer tick')
      }, 1000)
    })

    onBeforeUnmount(() => {
      if (intervalId) {
        clearInterval(intervalId)
        console.log('Timer cleaned up')
      }
    })

    return {}
  }
}

The onBeforeUnmount hook is called right before the component instance is unmounted and destroyed. This is the ideal place to clean up timers, cancel network requests, remove event listeners, and dispose of any resources that were created during the component’s lifecycle. The hook ensures that cleanup happens before the component is completely removed from the DOM and memory.

Best Practice Note:

This is the approach we use in CoreUI Vue components for cleaning up intervals, subscriptions, and external library instances. Always pair resource creation in onMounted with corresponding cleanup in onBeforeUnmount to prevent memory leaks and ensure optimal application performance.


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