Vue Lifecycle Hooks

Vue Tutorial

 Vue Lifecycle Hooks

Lifecycle hooks in Vue are special methods. They let you run code at specific stages of a component’s life. This includes stages from creation to removal from the DOM.

Vue lifecycle hooks are a key part of Vue.js. They are important for interviews, real projects, and improving performance.


 What is Vue Lifecycle?

Every Vue component goes through stages:

  1. Creation

  2. Mounting

  3. Updating

  4. Unmounting (Destroying)

  • Lifecycle hooks allow you to hook into these stages.

 Lifecycle Hooks Order (Very Important)

beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeUnmount
unmounted
  •  Interview favorite question: Explain lifecycle order

Creation Phase Hooks

beforeCreate()

  • Component instance created

  • data, props, methods NOT available


created()

  • data, props, methods available

  • DOM not available

 Best place for:

  • API calls

  • Initial data setup


 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


Updating Phase Hooks

beforeUpdate()

  • Data changed

  • DOM not updated yet


updated()

  • DOM updated after data change

  •  Avoid changing state here (can cause infinite loop)

Unmounting Phase Hooks

beforeUnmount()

  • Component about to be destroyed


unmounted()

  • Component removed from DOM

 Best place for:

  • Clearing intervals

  • Removing event listeners

  • Cleanup tasks


Lifecycle Hooks Example


Vue 2 vs Vue 3 Hook Names

Vue 2Vue 3
beforeDestroybeforeUnmount
destroyedunmounted
  •  Vue 3 uses Unmount, not Destroy

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

You may also like...