Episode 26 of 44
Life-cycle Hooks
Understand the Vue component lifecycle — run code at specific stages like creation, mounting, updating, and destruction.
Life-cycle Hooks
Every Vue component goes through a series of stages: creation, mounting to the DOM, updating, and destruction. Lifecycle hooks let you run code at each stage.
The Lifecycle Stages
| Hook | When It Runs | Common Use |
|---|---|---|
beforeCreate | Instance initialized, data not yet reactive | Rarely used |
created | Data is reactive, template not yet compiled | Fetch initial data, set up event listeners |
beforeMount | Template compiled, not yet inserted into DOM | Rarely used |
mounted | Component is in the DOM | Access DOM elements, start timers, third-party libs |
beforeUpdate | Data changed, DOM not yet updated | Access pre-update DOM state |
updated | DOM re-rendered after data change | Perform post-update DOM operations |
beforeDestroy | Component about to be destroyed | Clean up timers, event listeners |
destroyed | Component fully destroyed | Final cleanup |
Using Hooks
export default {
data() {
return { ninjas: [] };
},
created() {
// Fetch data when the component is created
fetch('/api/ninjas')
.then(res => res.json())
.then(data => { this.ninjas = data; });
},
mounted() {
console.log('Component mounted to DOM');
console.log(this.$el); // The root DOM element
},
beforeDestroy() {
// Clean up event bus listeners
bus.$off('title-changed');
}
};
Key Takeaways
createdis best for fetching data — the component's reactive data is readymountedruns after the component is in the DOM — access elements and start animationsbeforeDestroyis for cleanup — remove event listeners, clear timers- Hooks are defined as methods directly on the component options object