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

HookWhen It RunsCommon Use
beforeCreateInstance initialized, data not yet reactiveRarely used
createdData is reactive, template not yet compiledFetch initial data, set up event listeners
beforeMountTemplate compiled, not yet inserted into DOMRarely used
mountedComponent is in the DOMAccess DOM elements, start timers, third-party libs
beforeUpdateData changed, DOM not yet updatedAccess pre-update DOM state
updatedDOM re-rendered after data changePerform post-update DOM operations
beforeDestroyComponent about to be destroyedClean up timers, event listeners
destroyedComponent fully destroyedFinal 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

  • created is best for fetching data — the component's reactive data is ready
  • mounted runs after the component is in the DOM — access elements and start animations
  • beforeDestroy is for cleanup — remove event listeners, clear timers
  • Hooks are defined as methods directly on the component options object