Understanding Lifecycle Hooks

Explore Vue 2 lifecycle hooks, how they work, and when to use them through beginner-friendly examples.

🎯 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>
Use beforeCreate for early initialization logic. Since data has not been initialized, data properties and methods are unavailable.

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>
The created hook is useful for API requests and data initialization: component data is ready, but the DOM has not been created yet.

🚀 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>
Use mounted for DOM manipulation, initial page animations, and initializing third-party libraries.

🔄 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>
Update hooks can run frequently. Avoid heavy DOM operations or asynchronous requests inside them, as these may cause performance problems.

🧹 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>
Using destruction hooks appropriately helps prevent memory leaks and maintain application performance.

🔍 Lifecycle Hooks in Practice

Let's build a simple countdown component to demonstrate how lifecycle hooks work together.

example.vue
<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>
A countdown is a classic example of combining lifecycle hooks with data updates and timer cleanup.

❓ 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!