Lifecycle Hooks in Vue.js

🧩 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:

  1. Creation → before and after component setup
  2. Mounting → adding component to the DOM
  3. Updating → when data changes
  4. Unmounting → removing from the DOM

🧠 Common Lifecycle Hooks (Composition API)

HookWhen it RunsTypical Use
onBeforeMount()Before the component is mounted to the DOMSetup logic, event listeners (not DOM access yet)
onMounted()After the component is mountedAccess DOM elements, make API calls
onBeforeUpdate()Before re-render when reactive data changesInspect data before DOM updates
onUpdated()After the DOM updatesReact to DOM changes
onBeforeUnmount()Before component is removedCleanup (stop timers, remove listeners)
onUnmounted()After component is removedFinal 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 APIOptions 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:

HookDescription
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

PhaseHook(s)Purpose
Creationsetup()Initialize component state
MountingonBeforeMount, onMountedDOM setup, API calls
UpdatingonBeforeUpdate, onUpdatedRespond to data changes
UnmountingonBeforeUnmount, onUnmountedCleanup

Leave a Reply