By Rahul — Google Frontend Engineer
The Lifecycle Phases
Every Vue component goes through a series of initialization steps — setting up data observation, compiling templates, mounting to the DOM, and updating when data changes. Vue gives you hooks to run code at each phase.
The Hooks in Order
Creation Phase
beforeCreate() {
// Instance is created but data/methods NOT set up yet
// this.message → undefined
// Rarely used
}
created() {
// Data, computed, methods, watchers are ready
// DOM is NOT available yet
// BEST place for API calls
this.fetchData();
}Mounting Phase
beforeMount() {
// Template compiled, about to insert into DOM
// this.$el exists but is the raw template, not rendered
}
mounted() {
// Component is in the DOM
// Safe to access this.$el, this.$refs
// Initialize third-party libraries here
this.chart = new Chart(this.$refs.canvas, config);
}Update Phase
beforeUpdate() {
// Data changed, DOM not yet re-rendered
// Access the current DOM state before Vue updates it
}
updated() {
// DOM has been re-rendered
// Careful: modifying data here causes infinite loop!
}Destruction Phase
beforeDestroy() { // beforeUnmount in Vue 3
// Component is still functional
// Clean up: remove listeners, cancel timers, destroy charts
this.chart.destroy();
clearInterval(this.timer);
window.removeEventListener('resize', this.handleResize);
}
destroyed() { // unmounted in Vue 3
// Component is fully torn down
}Vue 3 Composition API Equivalents
import { onMounted, onBeforeUnmount, onUpdated } from 'vue';
setup() {
// setup() itself = created + beforeCreate
onMounted(() => {
// Same as mounted()
});
onBeforeUnmount(() => {
// Same as beforeDestroy()
});
onUpdated(() => {
// Same as updated()
});
}Production Issues
- Memory leak: Forgetting to clean up in beforeDestroy/beforeUnmount. Every addEventListener needs a removeEventListener
- API calls in mounted vs created: Use created for API calls — it runs earlier. Use mounted only when you need DOM access
- Infinite update loop: Modifying reactive data inside updated() triggers another update
- SSR gotcha: mounted() does NOT run on the server. Only beforeCreate and created run during SSR
Summary
Vue lifecycle goes: create → mount → update → destroy. Use created for data fetching, mounted for DOM access, and beforeDestroy for cleanup. In Vue 3, the Composition API provides the same hooks as functions.