Vue Lifecycle Hooks

Vue Lifecycle Hooks

Lifecycle hooks let you run code at specific stages of a component's life — from creation to destruction.

Composition API Lifecycle Hooks

import {
  onMounted,
  onUpdated,
  onUnmounted,
  onBeforeMount,
  onBeforeUpdate,
  onBeforeUnmount,
} from 'vue'

export default {
  setup() {
    onBeforeMount(() => {
      console.log('Before component is mounted')
    })

    onMounted(() => {
      console.log('Component mounted — DOM is ready')
      // fetch initial data, set up event listeners, init third-party libs
    })

    onUpdated(() => {
      console.log('Component updated — reactive data changed')
    })

    onBeforeUnmount(() => {
      console.log('Before component is destroyed')
      // clean up: remove event listeners, clear timers
    })

    onUnmounted(() => {
      console.log('Component destroyed')
    })
  }
}

Common Patterns

// Fetch data on mount
onMounted(async () => {
  users.value = await fetchUsers()
})

// Set up and tear down a resize listener
onMounted(() => {
  window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// Start and clear a timer
onMounted(() => {
  timer = setInterval(tick, 1000)
})
onUnmounted(() => {
  clearInterval(timer)
})
VueJS {"id":62,"topic_id":32,"name":"Composables and Reusability","slug":"composables-and-reusability","image":null,"description":"<p>Extract and reuse stateful logic across components using Vue composables.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":7,"created_at":"2026-05-04T20:50:50.000000Z","updated_at":"2026-05-04T20:50:50.000000Z"} - List of Contents

Related Tutorials: