Vue Lifecycle Hooks
⚙️ Vue Lifecycle Hooks
Vue lifecycle hooks are a key part of Vue.js. They are important for interviews, real projects, and improving performance.
1️⃣ What is Vue Lifecycle? ⭐
Every Vue component goes through stages:
-
Creation
-
Mounting
-
Updating
-
Unmounting (Destroying)
👉 Lifecycle hooks allow you to hook into these stages.
2️⃣ Lifecycle Hooks Order (Very Important) ⭐⭐⭐
📌 Interview favorite question: Explain lifecycle order
3️⃣ Creation Phase Hooks ⭐⭐
🔹 beforeCreate()
-
Component instance created
-
❌
data,props,methodsNOT available
🔹 created()
-
data,props,methodsavailable -
❌ DOM not available
✅ Best place for:
-
API calls
-
Initial data setup
4️⃣ Mounting Phase Hooks ⭐⭐
🔹 beforeMount()
-
Template compiled
-
DOM not yet inserted
🔹 mounted() ⭐⭐⭐
-
DOM fully available
-
Component rendered on screen
✅ Best place for:
-
DOM manipulation
-
Third-party libraries (charts, sliders)
-
Timers & event listeners
5️⃣ Updating Phase Hooks ⭐⭐
🔹 beforeUpdate()
-
Data changed
-
DOM not updated yet
🔹 updated()
-
DOM updated after data change
⚠️ Avoid changing state here (can cause infinite loop)
6️⃣ Unmounting Phase Hooks ⭐⭐
🔹 beforeUnmount()
-
Component about to be destroyed
🔹 unmounted()
-
Component removed from DOM
✅ Best place for:
-
Clearing intervals
-
Removing event listeners
-
Cleanup tasks
7️⃣ Lifecycle Hooks Example ⭐⭐⭐
8️⃣ Vue 2 vs Vue 3 Hook Names ⚠️
| Vue 2 | Vue 3 |
|---|---|
beforeDestroy |
beforeUnmount |
destroyed |
unmounted |
📌 Vue 3 uses Unmount, not Destroy
9️⃣ Lifecycle Hooks in Composition API ⭐⭐⭐
📌 Interview Questions (Vue Lifecycle)
Q1. Which hook is best for API calls?
👉 created()
Q2. Which hook has DOM access?
👉 mounted()
Q3. Cleanup code should go in?
👉 beforeUnmount() / unmounted()
Q4. Lifecycle hook order?
👉 Creation → Mounting → Updating → Unmounting
✅ Summary
✔ Lifecycle hooks control component behavior
✔ created() → data/API
✔ mounted() → DOM access
✔ updated() → reacts to data change
✔ unmounted() → cleanup
✔ Must-know for Vue interviews
