Understanding Lifecycle Hooks
🎯 Introduction
Understanding Vue 2 lifecycle hooks gives you control over component creation, updates, and destruction. These hooks help with everyday tasks such as data processing, state management, and performance optimization. This article walks through the key hooks and their uses so you can build more robust, flexible Vue components.
⚙️ Vue 2 Lifecycle Overview
The Vue 2 lifecycle is the sequence of stages a component instance passes through from creation to destruction. Vue automatically calls lifecycle hooks at specific points, letting you run code at the appropriate time. Understanding these hooks helps you organize application logic effectively.
The Vue 2 lifecycle has four main stages:
- Creation (beforeCreate, created)
- Mounting (beforeMount, mounted)
- Updating (beforeUpdate, updated)
- Destruction (beforeDestroy, destroyed)
Let's look at each in turn.
🛠️ Creation Hooks
beforeCreate
The component instance has just been created, but data observation and instance options such as data and methods have not been initialized. You cannot access data, computed properties, or methods yet.
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue2!',
};
},
beforeCreate() {
// Accessing this.message here returns undefined
console.log('beforeCreate:', this.message); // undefined
},
};
</script>
created
The component instance has been created and data observation is set up. You can access data, computed properties, and methods, but the DOM has not been mounted yet.
<script>
export default {
data() {
return {
message: 'Hello Vue2!',
};
},
created() {
console.log('created:', this.message); // Outputs "Hello Vue2!"
// Fetch data or initialize application logic here
},
};
</script>
🚀 Mounting Hooks
beforeMount
Template compilation is complete and mounting is about to begin, before the component is attached to the actual DOM.
<script>
export default {
beforeMount() {
console.log('beforeMount: About to mount on the page');
},
};
</script>
mounted
Called after the component is mounted on the page. You can now work with the actual DOM.
<template>
<div ref="myDiv">This is a div</div>
</template>
<script>
export default {
mounted() {
console.log('mounted: Component mounted');
// Access the actual DOM here
this.$refs.myDiv.style.color = 'blue';
},
};
</script>
🔄 Update Hooks
When component data changes and triggers a re-render, the lifecycle enters the update stage.
beforeUpdate
Called after data changes, before the virtual DOM is re-rendered.
<script>
export default {
data() {
return {
count: 0,
};
},
beforeUpdate() {
console.log('beforeUpdate: About to update the view; current count:', this.count);
},
};
</script>
updated
Called after the component's DOM has been updated.
<script>
export default {
updated() {
console.log('updated: DOM update complete');
},
};
</script>
🧹 Destruction Hooks
When a component is no longer needed, Vue destroys its instance and releases resources.
beforeDestroy
Called before the component is destroyed. Use this hook for cleanup.
<script>
export default {
beforeDestroy() {
console.log('beforeDestroy: Component is about to be destroyed');
// Clear timers, remove event listeners, and so on
},
};
</script>
destroyed
Called after the component has been destroyed, its event listeners have been removed, and its child instances have been destroyed.
<script>
export default {
destroyed() {
console.log('destroyed: Component destroyed');
},
};
</script>
🔍 Lifecycle Hooks in Practice
Let's build a simple countdown component to demonstrate how lifecycle hooks work together.
<template>
<div>
<p>Countdown: {{ seconds }} seconds</p>
<button @click="start">Start countdown</button>
</div>
</template>
<script>
export default {
data() {
return {
seconds: 10,
timer: null,
};
},
beforeCreate() {
console.log('beforeCreate: Initializing countdown component');
},
created() {
console.log('created: Countdown data ready');
},
mounted() {
console.log('mounted: Component mounted');
},
beforeUpdate() {
console.log('beforeUpdate: About to update the view; current seconds:', this.seconds);
},
updated() {
console.log('updated: Seconds updated:', this.seconds);
},
beforeDestroy() {
console.log('beforeDestroy: Destroying countdown component and clearing timer');
clearInterval(this.timer);
},
destroyed() {
console.log('destroyed: Countdown component destroyed');
},
methods: {
start() {
this.timer = setInterval(() => {
if (this.seconds > 0) {
this.seconds--;
} else {
clearInterval(this.timer);
}
}, 1000);
},
},
};
</script>
❓ Questions and Answers
Q1: Why can you not access data in beforeCreate?
At the beforeCreate stage, data has not been initialized or made observable, so its values are not yet available.
Q2: What is the difference between mounted and created?
The created hook runs when data is ready but the DOM has not been mounted. The mounted hook runs after the component is mounted in the actual DOM, allowing you to manipulate page elements.
Q3: How do you prevent memory leaks when a component is destroyed?
Clear timers, remove event listeners, and release resources in beforeDestroy so the component can be cleaned up properly.
🧪 Exercises
Exercise 1
Write a simple Vue 2 counter component. Initialize the count automatically in mounted and clear the timer in beforeDestroy.
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Add one</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
timer: null,
};
},
mounted() {
// Initialize the counter to 5
},
beforeDestroy() {
// Clear the timer
},
methods: {
increment() {
this.count++;
},
},
};
</script>
Exercise 2
Build a component that tracks data changes. Use beforeUpdate and updated to log the count during the update process.
<template>
<div>
<p>Click count: {{ count }}</p>
<button @click="count++">Click to increment</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
beforeUpdate() {
// Log count before the DOM update
},
updated() {
// Log count after the DOM update
},
};
</script>
🎉 You now understand Vue 2 lifecycle hooks, data binding, and component cleanup. Keep practicing to build high-quality Vue 2 applications!
Computed Properties and Watchers
Understand Vue 2.0 reactivity and learn practical techniques for computed properties and watchers.
Getting Started with Vue Router
Learn what single-page applications are, how client-side routing works, and how to install, configure, and use Vue Router in a Vue 2.0 project.
