Lifecycle hooks let you run code at important moments in a component's life, like when it starts or stops. This helps you manage tasks like fetching data or cleaning up.
Lifecycle hooks in Composition API in Vue
import { onMounted, onUnmounted, onUpdated, onBeforeMount, onBeforeUpdate } from 'vue'; export default { setup() { onMounted(() => { // code to run after component mounts }); onUnmounted(() => { // code to run before component unmounts }); onUpdated(() => { // code to run after component updates }); onBeforeMount(() => { // code to run before component mounts }); onBeforeUpdate(() => { // code to run before component updates }); } }
All lifecycle hooks are called inside the setup() function.
Each hook takes a function that runs at the right time.
import { onMounted } from 'vue'; export default { setup() { onMounted(() => { console.log('Component is now visible'); }); } }
import { onUnmounted } from 'vue'; export default { setup() { onUnmounted(() => { console.log('Component is about to be removed'); }); } }
import { onUpdated } from 'vue'; export default { setup() { onUpdated(() => { console.log('Component just updated'); }); } }
This component shows a count number and a button to increase it. It logs messages when the component mounts, updates, and unmounts, showing how lifecycle hooks work in the Composition API.
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increase</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, onUpdated } from 'vue';
const count = ref(0);
function increment() {
count.value++;
}
onMounted(() => {
console.log('Component mounted');
});
onUpdated(() => {
console.log('Component updated, count is', count.value);
});
onUnmounted(() => {
console.log('Component unmounted');
});
</script>Use onMounted to start tasks like fetching data.
Use onUnmounted to stop timers or remove event listeners to avoid memory leaks.
Hooks run only inside setup() or <script setup> in Vue 3.
Lifecycle hooks let you run code at key moments in a component's life.
Use hooks like onMounted and onUnmounted inside setup().
They help manage side effects like data fetching and cleanup.
Practice
Solution
Step 1: Understand the lifecycle phases
TheonMountedhook runs after the component is inserted into the DOM.Step 2: Match the hook to the action
Since the question asks for the hook that runs right after adding to the page,onMountedis the correct choice.Final Answer:
onMounted -> Option DQuick Check:
Mounted = after insert [OK]
- Confusing onMounted with onCreated
- Thinking onUpdated runs after mounting
- Using onDestroyed for setup tasks
onUnmounted hook inside the setup() function?Solution
Step 1: Check import syntax
The correct import uses curly braces:import { onUnmounted } from 'vue';Step 2: Check usage inside setup
The hook is called as a function with a callback:onUnmounted(() => { /* cleanup */ });Final Answer:
Correct import and call syntax -> Option BQuick Check:
Import with braces + call hook [OK]
- Importing without braces
- Assigning hook to a variable instead of calling
- Calling hook without a callback function
import { ref, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
onMounted(() => {
count.value = 5;
console.log('Mounted count:', count.value);
});
return { count };
}
}Solution
Step 1: Understand ref and onMounted
countstarts at 0, then insideonMountedit is set to 5 and logged.Step 2: Predict console output
The console logs 'Mounted count:' followed by the updated value 5.Final Answer:
Mounted count: 5 -> Option AQuick Check:
Value updated before log in onMounted [OK]
- Assuming count is still 0 inside onMounted
- Thinking onMounted runs before setup returns
- Confusing ref.value with ref itself
import { onMounted } from 'vue';
export default {
setup() {
onMounted = () => {
console.log('Mounted');
};
}
}Solution
Step 1: Check how onMounted is used
The code assigns a function toonMountedinstead of calling it with a callback.Step 2: Understand correct usage
The correct usage isonMounted(() => { ... }), not assignment.Final Answer:
onMounted is incorrectly assigned instead of called -> Option AQuick Check:
Hooks are called, not reassigned [OK]
- Assigning hook instead of calling it
- Forgetting to pass a function to onMounted
- Thinking setup must always return something
Solution
Step 1: Check data fetching on mount
import { ref, onMounted, onUnmounted } from 'vue'; export default { setup() { const data = ref(null); let timer; onMounted(() => { fetch('/api/data').then(res => res.json()).then(json => data.value = json); timer = setInterval(() => console.log('tick'), 1000); }); onUnmounted(() => { clearInterval(timer); }); return { data }; } }usesonMountedto fetch data and start the timer, which is correct.Step 2: Check cleanup on unmount
import { ref, onMounted, onUnmounted } from 'vue'; export default { setup() { const data = ref(null); let timer; onMounted(() => { fetch('/api/data').then(res => res.json()).then(json => data.value = json); timer = setInterval(() => console.log('tick'), 1000); }); onUnmounted(() => { clearInterval(timer); }); return { data }; } }usesonUnmountedto clear the timer, preventing memory leaks.Final Answer:
Correctly uses onMounted and onUnmounted hooks -> Option CQuick Check:
Fetch on mount + cleanup on unmount [OK]
- Starting timers outside lifecycle hooks
- Not clearing timers on unmount
- Fetching data outside onMounted
Ready to prove it?
Pass the test and this pattern moves unknown
