What is onBeforeUnmount in Vue: Explanation and Example
onBeforeUnmount is a Vue lifecycle hook that runs just before a component is removed from the page. It lets you clean up resources or stop tasks before the component disappears.How It Works
Imagine you have a room where you do some work, and before leaving, you want to tidy up and turn off the lights. onBeforeUnmount is like that moment before you leave the room. It runs right before Vue removes a component from the screen.
This hook gives you a chance to stop timers, cancel network requests, or remove event listeners that the component was using. Without this, leftover tasks might keep running and cause problems.
Vue calls onBeforeUnmount automatically when the component is about to be unmounted, so you don’t have to worry about calling it yourself.
Example
This example shows a component that starts a timer when it appears and stops it just before it disappears using onBeforeUnmount.
import { ref, onMounted, onBeforeUnmount } from 'vue'; export default { setup() { const count = ref(0); let timer = null; onMounted(() => { timer = setInterval(() => { count.value++; console.log('Count:', count.value); }, 1000); }); onBeforeUnmount(() => { clearInterval(timer); console.log('Timer stopped before component unmounts'); }); return { count }; } };
When to Use
Use onBeforeUnmount when you need to clean up before a component goes away. This includes:
- Stopping timers or intervals to avoid memory leaks.
- Removing event listeners added to the window or document.
- Cancelling ongoing network requests or subscriptions.
- Clearing any resources that should not persist after the component is gone.
For example, if you have a chat window component that listens for new messages, you should remove those listeners before the component unmounts to prevent errors or unexpected behavior.
Key Points
onBeforeUnmountruns just before a component is removed from the DOM.- It is used to clean up resources like timers, listeners, or subscriptions.
- Helps prevent memory leaks and unwanted side effects.
- Works only in Vue 3 with the Composition API.
Key Takeaways
onBeforeUnmount lets you run code before a Vue component is removed.onBeforeUnmount when your component no longer needs them.