0
0
Vueframework~3 mins

Why onMounted and onUnmounted in Vue? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your Vue components smart about when they start and stop doing things!

The Scenario

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.

The Problem

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.

The Solution

Vue's onMounted and onUnmounted hooks run code exactly when a component appears or disappears.

This makes starting and stopping tasks automatic and reliable.

Before vs After
Before
const timer = setInterval(() => console.log('tick'), 1000);
// forgot to clear timer when component removed
After
import { onMounted, onUnmounted } from 'vue';

let timer;

onMounted(() => {
  timer = setInterval(() => console.log('tick'), 1000);
});
onUnmounted(() => {
  clearInterval(timer);
});
What It Enables

You can easily manage setup and cleanup tasks tied to component life cycles without errors.

Real Life Example

Starting a live chat connection when a chat window opens and closing it when the user leaves.

Key Takeaways

onMounted runs code when a component appears.

onUnmounted runs code when a component disappears.

They help manage resources and side effects safely and cleanly.