Discover how to make your Vue components smart about when they start and stop doing things!
Why onMounted and onUnmounted in Vue? - Purpose & Use Cases
Imagine you have a webpage where you want to start a timer when a section appears and stop it when the section disappears.
You try to add and remove these timers manually every time the page changes.
Manually tracking when elements appear or disappear is tricky and easy to forget.
This can cause timers to keep running in the background, wasting resources or causing bugs.
Vue's onMounted and onUnmounted hooks run code exactly when a component appears or disappears.
This makes starting and stopping tasks automatic and reliable.
const timer = setInterval(() => console.log('tick'), 1000); // forgot to clear timer when component removed
import { onMounted, onUnmounted } from 'vue'; let timer; onMounted(() => { timer = setInterval(() => console.log('tick'), 1000); }); onUnmounted(() => { clearInterval(timer); });
You can easily manage setup and cleanup tasks tied to component life cycles without errors.
Starting a live chat connection when a chat window opens and closing it when the user leaves.
onMounted runs code when a component appears.
onUnmounted runs code when a component disappears.
They help manage resources and side effects safely and cleanly.