Mastering Vue 3 Lifecycle Hooks: A Complete Guide with Code Examples
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:
- "How do I fetch data when a component loads?"
- "How can I clean up before a component disappears?"
- "When should I update the DOM?"
ā¦then lifecycle hooks are your answer! Letās break them down in a simple, beginner-friendly way.
š Vue 3 Lifecycle Hooks: The Step-by-Step Journey
Every Vue component goes through a series of phases, and each has a corresponding hook. Hereās the full lifecycle flow:
1ļøā£ Creation Phase (Initialization & Setup)
These hooks run when your component is first created.
setup() (New in Vue 3!)
- The first thing that runs (even before the component is created!).
- Used with the Composition API to define data, methods, and more.
onBeforeMount()
- Runs right before the component is added to the DOM.
- Use case: Last-minute changes before rendering.
onMounted()
- Runs after the component is added to the DOM.
- Use case: Fetching API data, setting up event listeners.
import { onMounted } from 'vue';
export default {
setup() {
onMounted(() => {
console.log("Component is now on the page!");
});
}
}
2ļøā£ Updating Phase (Reactivity & Changes)
These hooks run when data changes and the component re-renders.
onBeforeUpdate()
- Runs before changes are applied to the DOM.
- Use case: Checking previous state before an update.
onUpdated()
- Runs after changes are applied to the DOM.
- Use case: Performing actions after Vue updates the page.
import { ref, onUpdated } from 'vue';
export default {
setup() {
const count = ref(0);
onUpdated(() => {
console.log("The count changed!");
});
return { count };
}
}
3ļøā£ Destruction Phase (Cleanup & Removal)
These hooks run when the component is removed from the page.
onBeforeUnmount()
- Runs before the component is destroyed.
- Use case: Cleaning up timers, event listeners.
onUnmounted()
- Runs after the component is destroyed.
- Use case: Final cleanup tasks.
import { onUnmounted } from 'vue';
export default {
setup() {
onUnmounted(() => {
console.log("Component is gone!");
});
}
}
šÆ Real-Life Example: Fetching Data on Mount
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!
š Key Takeaways
ā 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.
š” Frequently Asked Questions (FAQs)
Q1: Whatās the difference between onMounted and onCreated?
In Vue 3, onCreated doesnāt existāsetup() replaces it! onMounted runs after the component is in the DOM.
Q2: Can I use multiple lifecycle hooks?
Yes! You can call them multiple times in setup(), and theyāll run in order.
Q3: Do lifecycle hooks work with the Options API?
Yes! Vue 3 keeps beforeCreate, created, mounted, etc., but the Composition API (onMounted, etc.) is the modern way.
Letās Discuss!
Whatās the first thing youāll try with Vue lifecycle hooks?
Drop a comment below! š
Happy coding! šØāš»š©āš»
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
š Featuresā Google & GitHub Authenticationā User Registration & Loginā Profile/Dashboard Accessā Secure & Mi...
Flask Blog CMS with Admin Dashboard ā Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
š Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.