Kritim Yantra
Jul 22, 2025
Imagine you're baking a cake. 🎂 You don’t just throw all the ingredients in at once—you follow steps: preheating the oven, mixing the batter, baking, and finally decorating.
Vue components work the same way! They go through different stages—creation, updating, and destruction—and lifecycle hooks let you "hook into" these stages to run your own code at the right time.
If you’ve ever wondered:
…then lifecycle hooks are your answer! Let’s break them down in a simple, beginner-friendly way.
Every Vue component goes through a series of phases, and each has a corresponding hook. Here’s the full lifecycle flow:
These hooks run when your component is first created.
setup()
(New in Vue 3!)onBeforeMount()
onMounted()
import { onMounted } from 'vue';
export default {
setup() {
onMounted(() => {
console.log("Component is now on the page!");
});
}
}
These hooks run when data changes and the component re-renders.
onBeforeUpdate()
onUpdated()
import { ref, onUpdated } from 'vue';
export default {
setup() {
const count = ref(0);
onUpdated(() => {
console.log("The count changed!");
});
return { count };
}
}
These hooks run when the component is removed from the page.
onBeforeUnmount()
onUnmounted()
import { onUnmounted } from 'vue';
export default {
setup() {
onUnmounted(() => {
console.log("Component is gone!");
});
}
}
A common use case is loading data when a component appears:
import { ref, onMounted } from 'vue';
export default {
setup() {
const posts = ref([]);
onMounted(async () => {
const response = await fetch('https://api.example.com/posts');
posts.value = await response.json();
});
return { posts };
}
}
Now posts
will load automatically when the component mounts!
✔ setup()
– Where Composition API logic starts.
✔ onMounted()
– Perfect for API calls & DOM interactions.
✔ onUpdated()
– React to data changes after they happen.
✔ onUnmounted()
– Clean up to prevent memory leaks.
onMounted
and onCreated
?In Vue 3, onCreated
doesn’t exist—setup()
replaces it! onMounted
runs after the component is in the DOM.
Yes! You can call them multiple times in setup()
, and they’ll run in order.
Yes! Vue 3 keeps beforeCreate
, created
, mounted
, etc., but the Composition API (onMounted
, etc.) is the modern way.
What’s the first thing you’ll try with Vue lifecycle hooks?
Drop a comment below! 🚀
Happy coding! 👨💻👩💻
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google