Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue Lifecycle Hooks onMounted, onUnmounted: Tutorial, Examples, FAQs & Interview Tips

Component Lifecycle

Every Vue component goes through a series of initialization steps - creating reactive data, compiling the template, mounting to the DOM, updating when data changes, and unmounting. Lifecycle hooks let you run code at specific stages.

HookWhen it runsCommon use
onBeforeMountBefore component is mounted to DOMRarely needed
onMountedAfter component is mountedFetch data, access DOM, init libraries
onBeforeUpdateBefore DOM updatesAccess pre-update DOM state
onUpdatedAfter DOM updatesAccess updated DOM
onBeforeUnmountBefore component is destroyedCleanup (timers, listeners)
onUnmountedAfter component is destroyedFinal cleanup
onErrorCapturedWhen child throws errorError boundaries
Lifecycle Hooks - Practical Examples
<template>
  <div>
    <p>Users: {{ users.length }}</p>
    <p>Timer: {{ seconds }}s</p>
    <div ref="chartContainer"></div>
  </div>
</template>

<script setup>
import {
  ref, onBeforeMount, onMounted,
  onBeforeUpdate, onUpdated,
  onBeforeUnmount, onUnmounted,
  onErrorCaptured
} from 'vue'

const users = ref([])
const seconds = ref(0)
const chartContainer = ref(null)
let timer = null

// onBeforeMount - component not yet in DOM
onBeforeMount(() => {
  console.log('Before mount - DOM not ready yet')
})

// onMounted - component is in DOM, refs are available
onMounted(async () => {
  console.log('Mounted - DOM is ready')

  // 1. Fetch initial data
  const res = await fetch('/api/users')
  users.value = await res.json()

  // 2. Access DOM element via ref
  console.log('Chart container:', chartContainer.value)
  // initChart(chartContainer.value)  // init third-party library

  // 3. Start timer
  timer = setInterval(() => seconds.value++, 1000)

  // 4. Add event listener
  window.addEventListener('resize', handleResize)
})

// onBeforeUpdate - before DOM re-renders
onBeforeUpdate(() => {
  console.log('Before update - old DOM still accessible')
})

// onUpdated - after DOM re-renders
onUpdated(() => {
  console.log('Updated - DOM reflects new data')
  // Scroll to bottom of list after update
  // listEl.value.scrollTop = listEl.value.scrollHeight
})

// onBeforeUnmount - cleanup before destruction
onBeforeUnmount(() => {
  console.log('Before unmount - cleanup time')
  clearInterval(timer)
  window.removeEventListener('resize', handleResize)
})

// onUnmounted - component is gone
onUnmounted(() => {
  console.log('Unmounted - component destroyed')
})

// onErrorCaptured - catch errors from child components
onErrorCaptured((error, instance, info) => {
  console.error('Child error:', error, info)
  return false  // prevent error from propagating
})

function handleResize() {
  console.log('Window resized:', window.innerWidth)
}
</script>

Deep Dive: Lifecycle Hooks in Real Projects

Understanding Lifecycle Hooks is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Lifecycle Hooks.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Lifecycle Hooks.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Lifecycle Hooks focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.