Vue.js Lifecycle Hooks: Understanding Component Phases

Vue.js provides a set of lifecycle hooks that allow developers to execute code at specific stages of a component’s existence. Understanding these hooks helps in managing component behavior efficiently. In this article, we’ll explore different lifecycle hooks, their use cases, and best practices.

1. What Are Lifecycle Hooks?

Lifecycle hooks are special functions that Vue calls at different stages of a component’s lifecycle, from its creation to its destruction.

2. Lifecycle Stages and Hooks

Vue’s lifecycle can be divided into four main stages:

1. Creation (before component is mounted)

  • beforeCreate(): Runs before the component is initialized (data and props are not yet available).
  • created(): Runs after data and props are set up but before the component is mounted to the DOM.

2. Mounting (component is added to the DOM)

  • beforeMount(): Runs before the template is rendered in the DOM.
  • mounted(): Runs after the component is fully mounted; ideal for API calls and DOM interactions.

3. Updating (component reacts to data changes)

  • beforeUpdate(): Runs before the DOM updates; useful for debugging.
  • updated(): Runs after the DOM updates; use with caution to avoid infinite loops.

4. Unmounting (component is removed from the DOM)

  • beforeUnmount(): Runs before the component is removed; used for cleanup tasks.
  • unmounted(): Runs after the component is destroyed; useful for event listener removals.

3. Example: Using Lifecycle Hooks

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const count = ref(0);

onMounted(() => {
  console.log('Component mounted!');
});

onBeforeUnmount(() => {
  console.log('Component will be destroyed.');
});
</script>

<template>
  <p>Count: {{ count }}</p>
  <button @click="count++">Increase</button>
</template>

Here, onMounted runs when the component is added, and onBeforeUnmount executes before removal.

Leave a comment

Your email address will not be published. Required fields are marked *