Discover how to make your Vue components smart about their own life without messy code!
Why Lifecycle hooks in Composition API in Vue? - Purpose & Use Cases
Imagine you build a Vue app and want to run code when a component starts or stops, like fetching data when it appears or cleaning up timers when it disappears.
Without lifecycle hooks, you must manually track when components mount or unmount, which is confusing and easy to forget, causing bugs or wasted resources.
Lifecycle hooks in the Composition API let you run code at exact moments in a component's life, like setup, mount, update, and unmount, making your code clear and reliable.
mounted() { fetchData(); }, beforeDestroy() { clearTimer(); }onMounted(() => fetchData()); onBeforeUnmount(() => clearTimer());
You can easily control side effects and resource management tied to component life, improving app performance and user experience.
When a chat window opens, you start listening for new messages; when it closes, you stop listening to save memory and avoid errors.
Lifecycle hooks automate running code at key component moments.
They prevent bugs from forgotten setup or cleanup tasks.
Composition API hooks make this process simple and clear.
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
