These hooks let you run code right before a component appears on the screen or just before it disappears. This helps you prepare or clean up things smoothly.
You want to fetch data or set up something just before the component shows.
You need to start a timer or event listener before the component appears.
You want to stop timers or remove event listeners before the component goes away.
You want to save some state or clean resources before the component is removed.
You want to log or track when a component is about to mount or unmount.
Syntax
Vue
import { onBeforeMount, onBeforeUnmount } from'vue';
exportdefault {
setup() {
onBeforeMount(() => {
// code to run before mount
});
onBeforeUnmount(() => {
// code to run before unmount
});
}
}
Use these inside the setup() function of a Vue 3 component.
The functions you pass run once at the right time automatically.
Examples
This logs a message just before the component shows on screen.
This example has a parent with a button to show or hide a child component. The child logs messages just before it appears and just before it disappears.
B. onBeforeUnmount is assigned instead of called with a callback.
C. Arrow function syntax is incorrect.
D. setup() must return a value.
Solution
Step 1: Check how onBeforeUnmount is used
The code assigns a new function to onBeforeUnmount instead of calling it with a callback.
Step 2: Correct usage of onBeforeUnmount
It should be called like onBeforeUnmount(() => { ... }) to register the cleanup function.
Final Answer:
onBeforeUnmount is assigned instead of called with a callback. -> Option B
Quick Check:
Use onBeforeUnmount(callback), not assignment [OK]
Hint: Call onBeforeUnmount(callback), don't assign it [OK]
Common Mistakes:
Assigning lifecycle hook instead of calling it
Forgetting parentheses for function call
Confusing import errors with usage errors
5. You want to track how many times a component is about to mount and unmount using onBeforeMount and onBeforeUnmount. Which code correctly updates two counters mountCount and unmountCount inside setup()?