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.
Practice
onMounted lifecycle hook in Vue?Solution
Step 1: Understand the lifecycle timing of
TheonMountedonMountedhook runs after the component is inserted into the DOM and visible to the user.Step 2: Compare with other lifecycle hooks
onUnmountedruns before removal, and creation hooks run earlier. Updating data is reactive and not tied toonMounted.Final Answer:
To run code right after the component appears on the screen -> Option DQuick Check:
onMounted = runs after component appears [OK]
- Confusing onMounted with onUnmounted
- Thinking onMounted runs before creation
- Assuming onMounted updates data reactively
onUnmounted in a Vue 3 component with Composition API?Solution
Step 1: Recall the correct function call syntax
onUnmountedis a function that takes a callback function as an argument, so it must be called with parentheses and a function inside.Step 2: Check each option's syntax
onUnmounted(() => { console.log('Component removed') }) correctly callsonUnmountedwith an arrow function. Options B, C, and D have invalid syntax or missing parentheses.Final Answer:
onUnmounted(() => { console.log('Component removed') }) -> Option AQuick Check:
onUnmounted(callback) syntax correct [OK]
- Missing parentheses when calling onUnmounted
- Assigning onUnmounted instead of calling it
- Using incorrect braces or keywords
import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const count = ref(0)
let timer
onMounted(() => {
timer = setInterval(() => {
count.value++
}, 1000)
})
onUnmounted(() => {
clearInterval(timer)
})
return { count }
}
}What will happen to
count when the component is removed from the page?Solution
Step 1: Understand the timer setup in onMounted
The code starts a timer that incrementscountevery second when the component mounts.Step 2: Understand the cleanup in onUnmounted
The timer is cleared withclearInterval(timer)when the component unmounts, stopping the increments.Final Answer:
count will stop increasing because the timer is cleared on unmount -> Option BQuick Check:
onUnmounted clears timer stopping count increment [OK]
- Thinking count resets automatically on unmount
- Assuming timer keeps running after unmount
- Confusing onMounted and onUnmounted roles
import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const message = ref('Hello')
onMounted(() => {
console.log(message.value)
})
onUnmounted(() => {
console.log('Goodbye')
})
onMounted(() => {
console.log('Another mount')
})
return { message }
}
}Solution
Step 1: Check Vue 3 Composition API rules for lifecycle hooks
Vue 3 allows multipleonMountedhooks inside the same setup function; they run in the order declared.Step 2: Verify other options
There is no requirement foronUnmountedto be beforeonMounted, andmessagecan be declared outside hooks.Final Answer:
No error; multiple onMounted hooks are allowed and run in order -> Option AQuick Check:
Multiple onMounted hooks allowed [OK]
- Thinking only one onMounted hook is allowed
- Believing lifecycle hooks must be in specific order
- Assuming refs must be declared inside hooks
onMounted and onUnmounted to achieve this?import { onMounted, onUnmounted } from 'vue'
export default {
setup() {
let socket
// What should go here?
return {}
}
}Solution
Step 1: Understand lifecycle timing for resource management
Resources like WebSocket should be opened when the component appears (onMounted) and cleaned up before it disappears (onUnmounted).Step 2: Match options with correct lifecycle usage
Use onMounted to open the socket and onUnmounted to close it correctly usesonMountedto open andonUnmountedto close the socket. Other options misuse lifecycle hooks or open/close at wrong times.Final Answer:
Use onMounted to open the socket and onUnmounted to close it -> Option CQuick Check:
Open onMounted, close onUnmounted for resources [OK]
- Opening resource outside lifecycle hooks
- Closing resource in onMounted instead of onUnmounted
- Reversing open and close lifecycle hooks
Ready to prove it?
Pass the test and this pattern moves unknown
