0
0
Vueframework~15 mins

onMounted and onUnmounted in Vue - Deep Dive

Choose your learning style9 modes available
Overview - onMounted and onUnmounted
What is it?
onMounted and onUnmounted are special functions in Vue.js that let you run code when a component appears on the screen or disappears from it. onMounted runs right after the component is shown, and onUnmounted runs just before it is removed. They help you manage tasks like starting timers or cleaning up resources tied to the component's life.
Why it matters
Without onMounted and onUnmounted, you would have to manually track when components appear or disappear, which is error-prone and messy. These functions make it easy to run setup and cleanup code automatically, preventing bugs like memory leaks or unwanted background tasks. This keeps apps fast, clean, and reliable.
Where it fits
Before learning onMounted and onUnmounted, you should understand Vue components and the Composition API basics. After mastering these, you can explore more lifecycle hooks and advanced state management in Vue.
Mental Model
Core Idea
onMounted and onUnmounted let you run code exactly when a component starts and stops living on the page.
Think of it like...
It's like turning on a lamp when you enter a room (onMounted) and turning it off when you leave (onUnmounted).
Component Lifecycle
┌───────────────┐
│ Component     │
│ Created       │
│               │
│ ┌───────────┐ │
│ │ Mounted   │◄──── onMounted runs here
│ └───────────┘ │
│               │
│ ┌───────────┐ │
│ │ Unmounted │◄──── onUnmounted runs here
│ └───────────┘ │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Vue Component Lifecycle
🤔
Concept: Learn what happens when a Vue component is created, shown, and removed.
A Vue component goes through stages: creation, mounting (showing on screen), updating, and unmounting (removal). These stages let Vue manage the component's presence and behavior.
Result
You know the basic life stages of a Vue component.
Understanding the lifecycle is key to knowing when to run code related to a component's presence.
2
FoundationIntroduction to Composition API Setup
🤔
Concept: Learn how to write Vue components using the Composition API with setup() function.
The setup() function is where you define reactive data and functions for a component. It runs before the component is mounted.
Result
You can create a simple Vue component using setup().
Knowing setup() is essential because onMounted and onUnmounted are used inside it.
3
IntermediateUsing onMounted to Run Code on Show
🤔Before reading on: do you think onMounted runs before or after the component appears on screen? Commit to your answer.
Concept: onMounted runs a function right after the component is added to the page.
Inside setup(), you call onMounted(() => { /* code here */ }) to run code after the component appears. For example, start a timer or fetch data.
Result
Code inside onMounted runs once the component is visible.
Knowing onMounted runs after the component is visible helps you safely access DOM elements or start tasks.
4
IntermediateUsing onUnmounted to Clean Up
🤔Before reading on: do you think onUnmounted runs before or after the component disappears? Commit to your answer.
Concept: onUnmounted runs a function just before the component is removed from the page.
Inside setup(), you call onUnmounted(() => { /* cleanup code */ }) to stop timers, remove event listeners, or cancel tasks to avoid memory leaks.
Result
Cleanup code runs before the component is gone.
Cleaning up prevents bugs and wasted resources when components disappear.
5
IntermediatePractical Example: Timer with onMounted and onUnmounted
🤔
Concept: Combine onMounted and onUnmounted to start and stop a timer tied to the component.
In setup(), use onMounted to start a timer that updates a count every second. Use onUnmounted to clear the timer when the component is removed.
Result
The timer runs only while the component is visible and stops cleanly when gone.
This pattern shows how lifecycle hooks manage side effects safely.
6
AdvancedMultiple Lifecycle Hooks and Their Order
🤔Before reading on: do you think onMounted runs before or after onUpdated? Commit to your answer.
Concept: Learn how onMounted and onUnmounted fit with other lifecycle hooks like onUpdated.
onMounted runs once after the component is first shown. onUpdated runs after reactive data changes cause updates. onUnmounted runs once before removal. Understanding order helps manage complex behaviors.
Result
You can predict when each hook runs during component life.
Knowing hook order prevents bugs from running code too early or too late.
7
ExpertAvoiding Memory Leaks with onUnmounted
🤔Before reading on: do you think forgetting onUnmounted cleanup causes visible bugs immediately or subtle slowdowns? Commit to your answer.
Concept: Forgetting to clean up in onUnmounted can cause memory leaks and performance issues.
If you start timers, event listeners, or subscriptions in onMounted but don't stop them in onUnmounted, they keep running even after the component is gone. This wastes memory and CPU.
Result
Proper cleanup keeps apps fast and stable over time.
Understanding cleanup importance helps avoid hard-to-find bugs in large apps.
Under the Hood
Vue tracks component instances and their lifecycle states internally. When a component is mounted, Vue calls all registered onMounted callbacks after rendering the DOM. When a component is about to be removed, Vue calls onUnmounted callbacks to let you clean up. These hooks are stored in the component's internal lifecycle hook lists and triggered at the right time during the virtual DOM patching process.
Why designed this way?
Vue's lifecycle hooks were designed to give developers precise control over side effects tied to component presence. This avoids mixing setup code with rendering logic and prevents resource leaks. The Composition API introduced onMounted and onUnmounted to replace older options-based hooks with a more flexible, function-based approach that fits modern JavaScript patterns.
Vue Component Lifecycle Internals
┌─────────────────────────────┐
│ Component Instance Created   │
│                             │
│ ┌─────────────────────────┐ │
│ │ onMounted callbacks list │◄───── Registered during setup()
│ └─────────────────────────┘ │
│                             │
│ ┌─────────────────────────┐ │
│ │ onUnmounted callbacks list│◄──── Registered during setup()
│ └─────────────────────────┘ │
│                             │
│ Mounting Phase:             │
│ ──> Render DOM              │
│ ──> Call onMounted hooks    │
│                             │
│ Unmounting Phase:           │
│ ──> Call onUnmounted hooks  │
│ ──> Remove DOM              │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does onMounted run before the component is visible or after? Commit to your answer.
Common Belief:onMounted runs before the component appears on screen.
Tap to reveal reality
Reality:onMounted runs after the component is fully mounted and visible in the DOM.
Why it matters:Running code too early can cause errors if you try to access DOM elements that don't exist yet.
Quick: Does onUnmounted run after the component is removed or before? Commit to your answer.
Common Belief:onUnmounted runs after the component is removed from the DOM.
Tap to reveal reality
Reality:onUnmounted runs just before the component is removed, allowing cleanup while DOM is still accessible.
Why it matters:If cleanup runs too late, you can't properly remove event listeners or timers, causing memory leaks.
Quick: If you forget to use onUnmounted, will your app crash immediately? Commit to your answer.
Common Belief:Forgetting onUnmounted cleanup causes immediate crashes.
Tap to reveal reality
Reality:It usually causes subtle memory leaks and slow performance over time, not instant crashes.
Why it matters:Ignoring cleanup leads to hard-to-debug slowdowns and resource waste in large apps.
Quick: Can you use onMounted outside the setup() function? Commit to your answer.
Common Belief:You can call onMounted anywhere in the component code.
Tap to reveal reality
Reality:onMounted must be called inside setup() or a lifecycle-aware context to work correctly.
Why it matters:Calling it elsewhere means the hook won't register, and your code won't run at the right time.
Expert Zone
1
onMounted callbacks run after the DOM is patched but before the browser paints, allowing DOM reads but careful with heavy work.
2
Multiple onMounted or onUnmounted calls in the same component run in the order they were registered, which can affect side effect timing.
3
Using onUnmounted to cancel async operations requires careful handling to avoid setting state on unmounted components.
When NOT to use
Avoid using onMounted and onUnmounted for global app-wide effects; use Vue plugins or global state management instead. For simple reactive data, prefer watch or computed properties. Also, avoid heavy synchronous work in onMounted to keep UI responsive.
Production Patterns
In real apps, onMounted often starts data fetching or subscriptions, while onUnmounted cleans up event listeners or cancels timers. Complex components may stack multiple lifecycle hooks to manage nested resources. Experts also use onUnmounted to unregister global event handlers added outside Vue.
Connections
Event Listeners in JavaScript
onMounted and onUnmounted manage adding and removing event listeners safely.
Understanding how to add and remove event listeners in plain JavaScript helps grasp why cleanup in onUnmounted is critical to avoid leaks.
Resource Management in Operating Systems
Both manage allocation and cleanup of resources tied to a lifecycle.
Knowing OS resource management clarifies why components must clean up timers or listeners to prevent resource exhaustion.
Project Management: Task Start and End
Starting a task onMounted and ending it onUnmounted mirrors starting and closing tasks in project workflows.
Seeing lifecycle hooks as task boundaries helps plan code that runs only when needed, improving efficiency.
Common Pitfalls
#1Starting a timer in onMounted but forgetting to clear it in onUnmounted.
Wrong approach:onMounted(() => { timer = setInterval(() => console.log('tick'), 1000); });
Correct approach:onMounted(() => { timer = setInterval(() => console.log('tick'), 1000); }); onUnmounted(() => { clearInterval(timer); });
Root cause:Not understanding that timers keep running after component removal unless explicitly stopped.
#2Trying to access DOM elements before onMounted runs.
Wrong approach:setup() { const el = document.querySelector('#my'); console.log(el); }
Correct approach:onMounted(() => { const el = document.querySelector('#my'); console.log(el); });
Root cause:Assuming DOM is ready during setup(), but it is only ready after mounting.
#3Calling onMounted outside setup(), like in methods or lifecycle hooks options.
Wrong approach:methods: { init() { onMounted(() => { console.log('Hi'); }); } }
Correct approach:setup() { onMounted(() => { console.log('Hi'); }); }
Root cause:Misunderstanding that Composition API hooks must be called in setup() to register properly.
Key Takeaways
onMounted runs code after a Vue component appears on the page, perfect for starting tasks that need the DOM.
onUnmounted runs code just before the component disappears, letting you clean up timers, listeners, or other resources.
Using these hooks prevents bugs like memory leaks and ensures your app stays fast and stable.
They must be used inside the setup() function of the Composition API to work correctly.
Understanding the component lifecycle and hook order helps you write predictable and efficient Vue components.