🧩 What Are Lifecycle Hooks?
Every Vue component goes through a lifecycle — from creation to destruction.
Lifecycle hooks are special functions that let you run code at specific stages of that process.
⚙️ Lifecycle Flow (Composition API)
When a component is used, Vue goes through these main stages:
- Creation → before and after component setup
- Mounting → adding component to the DOM
- Updating → when data changes
- Unmounting → removing from the DOM
🧠 Common Lifecycle Hooks (Composition API)
| Hook | When it Runs | Typical Use |
|---|---|---|
onBeforeMount() | Before the component is mounted to the DOM | Setup logic, event listeners (not DOM access yet) |
onMounted() | After the component is mounted | Access DOM elements, make API calls |
onBeforeUpdate() | Before re-render when reactive data changes | Inspect data before DOM updates |
onUpdated() | After the DOM updates | React to DOM changes |
onBeforeUnmount() | Before component is removed | Cleanup (stop timers, remove listeners) |
onUnmounted() | After component is removed | Final cleanup, cancel requests |
🧩 Example:
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="count++">Increment</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUpdated, onUnmounted } from 'vue'
const count = ref(0)
onMounted(() => {
console.log('Component mounted!')
})
onUpdated(() => {
console.log('Component updated! Count =', count.value)
})
onUnmounted(() => {
console.log('Component destroyed!')
})
</script>
✅ Console Output example:
Component mounted!
Component updated! Count = 1
Component updated! Count = 2
Component destroyed!
🧱 Options API Equivalent
If you’re using the Options API (classic Vue syntax):
| Composition API | Options API |
|---|---|
onMounted() | mounted() |
onBeforeMount() | beforeMount() |
onUpdated() | updated() |
onBeforeUpdate() | beforeUpdate() |
onUnmounted() | unmounted() |
onBeforeUnmount() | beforeUnmount() |
setup() | created() / beforeCreate() (roughly equivalent) |
Example (Options API):
<script>
export default {
data() {
return { count: 0 }
},
mounted() {
console.log('mounted!')
},
updated() {
console.log('updated!')
},
unmounted() {
console.log('destroyed!')
}
}
</script>
🧰 Additional Hooks
Some less common but useful ones:
| Hook | Description |
|---|---|
onActivated() | When a <KeepAlive> component is activated |
onDeactivated() | When a <KeepAlive> component is deactivated |
onErrorCaptured() | Catch errors from child components |
onRenderTracked() | Debug when reactive dependencies are tracked |
onRenderTriggered() | Debug when reactivity triggers a re-render |
⚖️ Summary
| Phase | Hook(s) | Purpose |
|---|---|---|
| Creation | setup() | Initialize component state |
| Mounting | onBeforeMount, onMounted | DOM setup, API calls |
| Updating | onBeforeUpdate, onUpdated | Respond to data changes |
| Unmounting | onBeforeUnmount, onUnmounted | Cleanup |
