Vue Reference Documentation
Estimated reading: 4 minutes 26 views

πŸ”„ Vue Lifecycle Hooks Reference – Understand & Harness Each Phase (2025 Guide)


🧲 Introduction – What Are Vue Lifecycle Hooks?

Vue components go through a well-defined lifecycle from creation to destruction. Vue provides lifecycle hooks, which are methods you can use to run custom logic at each stageβ€”such as before mounting, after updates, or before the component is removed.

🎯 In this guide, you’ll learn:

  • All Vue lifecycle hooks in order
  • When and how to use each hook
  • Real-world examples and debugging tips
  • Differences in Vue 2 vs Vue 3 (Options API vs Composition API)

πŸ“˜ Lifecycle Stages Overview

StageHooks (Options API)
InitializationbeforeCreate, created
MountingbeforeMount, mounted
UpdatingbeforeUpdate, updated
UnmountingbeforeUnmount, unmounted
Error HandlingerrorCaptured, renderTracked, renderTriggered

Vue 3 replaces destroyed and beforeDestroy with unmounted and beforeUnmount.


πŸ” Lifecycle Hook Flow (Options API)

beforeCreate β†’ created β†’ beforeMount β†’ mounted
β†’ beforeUpdate β†’ updated
β†’ beforeUnmount β†’ unmounted

πŸ§ͺ Options API – Hook Examples

1. πŸ”Ή beforeCreate()

Runs before data, props, or methods are set up.

beforeCreate() {
  console.log('beforeCreate');
}

2. πŸ”Ή created()

Called after reactive properties are defined but before DOM is mounted.

created() {
  console.log('Data:', this.someData);
}

3. πŸ”Ή beforeMount()

Runs just before mounting to the DOM.

beforeMount() {
  console.log('DOM not yet mounted');
}

4. πŸ”Ή mounted()

The component is now mounted on the DOM. Great for accessing DOM elements via this.$el.

mounted() {
  console.log('DOM ready:', this.$el);
}

5. πŸ”Ή beforeUpdate()

Called before a reactive update is patched to the DOM.

beforeUpdate() {
  console.log('State changing...');
}

6. πŸ”Ή updated()

Runs after the DOM has been patched.

updated() {
  console.log('DOM updated!');
}

7. πŸ”Ή beforeUnmount() (Vue 3 only)

Runs just before the component is removed from the DOM.

beforeUnmount() {
  console.log('Component about to be destroyed');
}

8. πŸ”Ή unmounted() (Vue 3 only)

Called after the component has been removed from the DOM.

unmounted() {
  console.log('Component removed');
}

⚠️ Special Hooks

πŸ› οΈ errorCaptured(err, vm, info)

Catches errors in child components.

errorCaptured(err, vm, info) {
  console.error('Error:', err);
  return false; // stops error from propagating
}

πŸ” renderTracked() and renderTriggered() (Debug only)

Used to track reactivity dependencies.


βš›οΈ Composition API – Hook Alternatives

Use onMounted, onUpdated, onUnmounted, etc., inside setup():

import { onMounted, onUnmounted } from 'vue';

setup() {
  onMounted(() => {
    console.log('Component mounted!');
  });

  onUnmounted(() => {
    console.log('Component removed!');
  });
}

🧰 Real-World Examples

βœ… Data Fetching

mounted() {
  fetch('/api/data')
    .then(res => res.json())
    .then(data => this.items = data);
}

βœ… DOM Event Listener

mounted() {
  window.addEventListener('resize', this.handleResize);
},
unmounted() {
  window.removeEventListener('resize', this.handleResize);
}

βœ… Polling or Interval Logic

created() {
  this.timer = setInterval(this.pollData, 1000);
},
unmounted() {
  clearInterval(this.timer);
}

🧠 Best Practices

TipWhy It Matters
Use created() for API callsEnsures data is reactive before render
Use mounted() for DOM manipulationthis.$el is only available after mount
Clean up timers or events in unmounted()Avoids memory leaks
Avoid logic in beforeCreate()Reactive data not yet available

πŸ“Œ Summary – Recap & Next Steps

Vue lifecycle hooks are essential for managing side effects, state changes, and cleanup in your components. Mastering them allows you to write clean, maintainable logic that follows Vue’s reactivity flow.

πŸ” Key Takeaways:

  • Lifecycle hooks manage component behavior from creation to destruction
  • Use created() for setup, mounted() for DOM, and unmounted() for cleanup
  • Composition API hooks (e.g., onMounted) provide more modularity
  • Use errorCaptured() for safe component trees

βš™οΈ Real-World Relevance:
Useful in real apps for form setup, fetching data, animations, event listeners, and custom cleanup logic.


❓ FAQ Section

❓ What is the difference between created() and mounted()?

βœ… created() runs before the DOM is mounted; mounted() runs after the DOM is attached.


❓ Which hook is best for data fetching?

βœ… created() is ideal for logic not dependent on DOM; mounted() if DOM interaction is required.


❓ Can I use both Options and Composition API hooks?

βœ… Yes, but it’s recommended to choose one consistently per component.


❓ How do I clean up events in Vue?

βœ… Use unmounted() or onUnmounted() to remove event listeners and clear timers.


❓ Are beforeDestroy and destroyed still used in Vue 3?

βœ… No, they are replaced with beforeUnmount() and unmounted() in Vue 3.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Vue Lifecycle Hooks Reference

Or Copy Link

CONTENTS
Scroll to Top