DEV Community

Emperor Brains
Emperor Brains

Posted on

Exploring Vue 3 Lifecycle Hooks: A Hands-On Guide with Real-Time Examples

Image description

In the vast landscape of JavaScript frameworks, one name stands out as a favorite among developers — Vue.js, the framework that has captured the hearts of many with its simplicity and flexibility. And at the core of Vue.js lies a powerful feature: Lifecycle Hooks.

Lifecycle hooks in Vue.js provide developers with the ability to perform specific actions at crucial moments in a component’s existence. As a Vue component, essentially a view file in Vue.js, takes shape, it undergoes a sequence of essential initialization steps. These steps involve processes such as data observation, template compilation, mounting the instance to the DOM, and updating the DOM dynamically as the underlying data changes.

Every Vue component is, in essence, a Vue instance, and understanding how to leverage lifecycle hooks allows developers to tailor the component’s behavior at distinct stages of its lifecycle.

In this blog post, we will unravel the intricacies of Vue 3 lifecycle hooks, accompanied by a real-time example that will shed light on their practical application.

To add a touch of relatability to this exploration, let’s draw a parallel between the workings of Vue 3 lifecycle hooks and Bob’s morning routine. By comparing the meticulous steps Bob takes each morning with the meticulous treatment each lifecycle hook bestows upon our Vue component instances, we aim to demystify and simplify the understanding of these hooks.

So, buckle up as we dive deep into the world of Vue 3 lifecycle hooks and embark on a journey to comprehend how they sculpt the behavior of our Vue components.

Vuejs 3 lifecycle main hooks

beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeUnmount
unmounted

beforeCreate Hook in Vue.js

The beforeCreate hook is a lifecycle hook in Vue.js that is triggered immediately when a component instance is initialized. This occurs after the resolution of props but before the execution of other lifecycle hooks such as data() or computed. This hook provides an early entry point to perform actions or setups before the component fully initializes.

It’s important to note that in the Composition API, specifically in the setup() function, hooks are executed even before the beforeCreate hook. This means that any logic or operations defined in the setup() function will run before the beforeCreate hook is triggered. Below is an example to illustrate this sequencing:

// Example Vue.js component using the Composition API
import { ref, onBeforeCreate } from 'vue';

export default {
  setup() {
    // Code within setup() runs before beforeCreate hook
    console.log('Code inside setup()');

    // onBeforeCreate hook can still be used for specific actions
    onBeforeCreate(() => {
      console.log('beforeCreate hook');
      // Additional actions before other lifecycle hooks
    });

    // Return reactive data, refs, or other configurations
    return {
      exampleData: ref('Hello, Vue!'),
    };
  },

  // Other lifecycle hooks like created(), mounted(), etc. can follow
};
Enter fullscreen mode Exit fullscreen mode

In this example, the code within the setup() function is executed before the beforeCreate hook. This demonstrates the order of execution and emphasizes the role of beforeCreate in the component's lifecycle.

created Hook in Vue.js

The created hook is a lifecycle hook in Vue.js that is called after the component instance has finished processing all state-related options, including the data() and computed hooks. At this point, the component has been fully initialized, and reactive data, computed properties, and methods are available for use.

This hook is commonly used to perform actions that require access to the component’s state and configurations, making it a suitable place for additional setup, data fetching, or any logic that depends on the initialized state of the component.

Here’s an example illustrating the use of the created hook:

export default {
  data() {
    return {
      message: 'Hello, Vue!',
    };
  },

  computed: {
    reversedMessage() {
      return this.message.split('').reverse().join('');
    },
  },

  created() {
    // Accessing reactive data and computed properties
    console.log('Message:', this.message);
    console.log('Reversed Message:', this.reversedMessage);

    // Perform additional setup or async operations if needed
    // For example, fetching data from an API
    this.fetchData();
  },

  methods: {
    async fetchData() {
      // Simulating data fetching from an API
      // Await an asynchronous operation, like an Axios request
      console.log('Fetching data...');
      // Example: const response = await axios.get('/api/data');
      // Process the response and update the component's state
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

In this example, the created hook is used to log information about the reactive data and computed properties, as well as initiate a data fetching operation. This showcases how the hook can be employed for post-initialization tasks in a Vue.js component.

beforeMount Hook in Vue.js

The beforeMount hook is a lifecycle hook in Vue.js that is called right before the component is about to be mounted to the DOM. At this stage, the component has completed the setup of its reactive state, including data, computed properties, and methods. However, no DOM nodes associated with the component have been created yet. The beforeMount hook provides an opportunity to perform actions or setup tasks just before the component's initial render.

When the beforeMount hook is triggered, the component is on the verge of executing its DOM render effect for the first time. This makes it a suitable point to make final adjustments or execute logic that needs to be performed prior to the component becoming visible in the DOM.

Here’s an example demonstrating the use of the beforeMount hook:

export default {
  data() {
    return {
      message: 'Hello, Vue!',
    };
  },

  beforeMount() {
    // Accessing reactive data or performing setup before mounting
    console.log('Before Mount: Message is', this.message);

    // You might perform additional tasks or interact with third-party libraries
    // just before the component is mounted to the DOM.
    // For example, initializing a chart library or setting up event listeners.
    this.initializeChart();
  },

  mounted() {
    // At this point, the component has been mounted to the DOM.
    // You can perform actions that require access to the DOM elements.
    console.log('Mounted: Component has been mounted to the DOM');
  },

  methods: {
    initializeChart() {
      // Example: Initializing a chart library (not an actual implementation)
      console.log('Initializing chart...');
      // Code to set up a chart using a third-party library, e.g., Chart.js
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

In this example, the beforeMount hook is used to log information about the reactive data and to initialize a chart library just before the component is mounted. This illustrates the role of the beforeMount hook in facilitating pre-mount setup tasks.

mounted Hook in Vue.js

The mounted hook is a lifecycle hook in Vue.js that is called after the component or instance has been successfully mounted to the DOM. At this stage, the component's template has been rendered, and its associated DOM elements are now part of the document. The mounted hook is commonly used for performing side effects, initialization tasks, or any operations that require access to the component's rendered DOM.

Key points about the mounted hook:

  1. DOM Accessibility: Since the mounted hook is called after the component is attached to the DOM, it provides a suitable point for accessing and manipulating the DOM elements associated with the component.

2 . Initialization Tasks: It is often used to trigger actions that should occur once the component is fully visible in the document. This includes setting up event listeners, fetching additional data, or initializing third-party libraries.

Here’s an example illustrating the use of the mounted hook:

export default {
  data() {
    return {
      message: 'Hello, Vue!',
    };
  },

  mounted() {
    // Accessing the DOM elements after the component has been mounted
    const element = this.$el;
    console.log('Mounted: Component has been mounted to the DOM');

    // Perform side effects or initialization tasks that require DOM access
    this.setupEventListeners();
  },

  methods: {
    setupEventListeners() {
      // Example: Setting up a click event listener on a button
      const button = this.$el.querySelector('button');
      if (button) {
        button.addEventListener('click', this.handleButtonClick);
      }
    },

    handleButtonClick() {
      // Event handler logic
      console.log('Button clicked!');
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

In this example, the mounted hook is utilized to access the DOM elements after the component has been mounted and to set up an event listener on a button. This demonstrates how the hook is commonly used for tasks that require interaction with the rendered DOM.

beforeUpdate Hook in Vue.js

The beforeUpdate hook is a lifecycle hook in Vue.js that is called right before the component is about to update its DOM tree due to a reactive state change. It provides a useful opportunity to access and modify the component's state or the DOM state before the actual update takes place.

Key points about the beforeUpdate hook:

DOM State Access: This hook allows you to access both the component’s state and the DOM state just before Vue updates the DOM. It is particularly useful for making modifications or performing actions that should occur before the visual representation of the component is updated.
Safe State Modification: Unlike some lifecycle hooks, it is safe to modify the component’s state within the beforeUpdate hook. This makes it a suitable place to adjust data or perform calculations based on the current state before the update.
Conditional Updates: Use cases include conditional updates, where certain modifications to the DOM or component state need to happen based on specific conditions before the update is applied.
Here’s an example demonstrating the use of the beforeUpdate hook:

export default {
  data() {
    return {
      imageUrl: 'original-image.jpg',
      imageWidth: 100,
    };
  },

  beforeUpdate() {
    // Accessing and modifying the component state or DOM state before the update
    console.log('Before Update: Current Image Width is', this.imageWidth);

    // Example: Modify image width before the actual update
    this.imageWidth = this.calculateNewImageWidth();
  },

  updated() {
    // After the update, the component's state and the DOM have been synchronized
    console.log('Updated: Image updated with new width', this.imageWidth);
  },

  methods: {
    calculateNewImageWidth() {
      // Example: Calculate a new width based on some condition
      return Math.random() > 0.5 ? 150 : 80;
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

In this example, the beforeUpdate hook is used to access and modify the image width before the component updates. This demonstrates how the hook can be valuable for scenarios where pre-update adjustments are necessary.

updated Hook in Vue.js

The updated hook is a lifecycle hook in Vue.js that is called after the component has successfully updated its DOM tree due to a reactive state change. It signals that the component's state and the corresponding DOM elements have been synchronized.

Key points about the updated hook:

DOM Synchronization: This hook is triggered after any DOM update caused by reactive state changes in the component. It provides confirmation that the component’s template has been re-rendered to reflect the updated state.
No Information on Cause: While the updated hook informs you that an update has occurred, it doesn't provide specific details about what caused the update. For understanding the cause of changes, watchers are more appropriate.
Caution on DOM Updates: It is generally not recommended to perform direct DOM updates within the updated hook, as this hook can be triggered multiple times during the component's lifecycle. For DOM manipulations, it's often more appropriate to use other lifecycle hooks or directives.
Here’s an example illustrating the use of the updated hook:

export default {
  data() {
    return {
      message: 'Hello, Vue!',
    };
  },

  updated() {
    // This hook is called after any update to the component's DOM
    console.log('Updated: Component has been updated with new state');

    // Avoid direct DOM updates here to prevent potential issues
    // Use this hook for side effects that don't involve modifying the DOM directly
  },

  methods: {
    updateMessage() {
      // Example: Changing the message triggers a reactive state change
      this.message = 'Updated Message!';
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

In this example, the updated hook is utilized to log a message indicating that the component has been updated. It emphasizes the caution against performing direct DOM updates inside this hook, redirecting such operations to more appropriate lifecycle hooks or directives.

beforeUnmount Hook in Vue.js

The beforeUnmount hook is a lifecycle hook in Vue.js that is called right before a component instance is about to be unmounted, providing an opportunity for cleanup tasks before the component is destroyed.

Key points about the beforeUnmount hook:

Cleanup Operations: This hook is particularly useful for performing cleanup operations, such as clearing intervals, deregistering event listeners, or releasing resources, before the component is permanently removed from the DOM.
Replacement for Vue 2’s beforeDestroy: In Vue 2, the equivalent hook was named beforeDestroy. In Vue 3, the naming was changed to beforeUnmount to better align with the updated component lifecycle terminology.
Here’s an example demonstrating the use of the beforeUnmount hook:

export default {
  data() {
    return {
      intervalId: null,
    };
  },

  beforeUnmount() {
    // Cleanup operations before the component is unmounted
    console.log('Before Unmount: Cleaning up resources');

    // Clearing an interval as an example of cleanup
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },

  mounted() {
    // Set up an interval as an example
    this.intervalId = setInterval(() => {
      console.log('Interval tick');
    }, 1000);
  },
};
Enter fullscreen mode Exit fullscreen mode

In this example, the beforeUnmount hook is used to clean up resources (clearing an interval) before the component is unmounted. This illustrates the importance of this hook in managing cleanup tasks just before the component is removed from the DOM.

unmounted Hook in Vue.js

The unmounted hook is the final lifecycle hook in Vue.js, called after the component has been successfully unmounted and destroyed. At this stage, the component's DOM elements have been removed, and any resources or event listeners associated with the component should be released.

Key points about the unmounted hook:

Final Cleanup: The unmounted hook provides a final opportunity for cleanup operations that should be performed after the component is no longer part of the DOM. This is the last stop in the component's lifecycle.
No Access to Component State: It’s important to note that variables or state initialized within the component are not accessible within the unmounted hook. Any resources or data specific to the component should be handled and cleaned up in earlier hooks, such as beforeUnmount.
Here’s an example illustrating the use of the unmounted hook:

export default {
  data() {
    return {
      intervalId: null,
    };
  },

  beforeUnmount() {
    // Cleanup operations before unmounting
    console.log('Before Unmount: Cleaning up resources');

    // Clearing an interval as an example of cleanup
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },

  mounted() {
    // Set up an interval as an example
    this.intervalId = setInterval(() => {
      console.log('Interval tick');
    }, 1000);
  },

  unmounted() {
    // This hook is called after the component is completely unmounted
    console.log('Unmounted: Component has been successfully unmounted');
  },
};
Enter fullscreen mode Exit fullscreen mode

In this example, the unmounted hook is used to log a message indicating that the component has been successfully unmounted. The cleanup operations are handled in the beforeUnmount hook, emphasizing the separation of concerns between cleanup and the final acknowledgment of unmounting.

Embracing Innovation: A Vue.js Lifecycle Hooks Journey with Emperor Brains

Emperor Brains stands as a beacon of innovation and expertise in the realm of technology solutions. Through a deep dive into the intricacies of Vue.js 3 lifecycle hooks, we’ve demonstrated not only a commitment to understanding cutting-edge technologies but also a dedication to simplifying complex concepts for developers.

Emperor Brains recognizes the pivotal role that Vue.js lifecycle hooks play in shaping dynamic and responsive web applications. Our exploration, coupled with real-time examples, serves as a testament to our mission of empowering developers with practical insights and knowledge.

As a technology-focused company, Emperor Brains encourages developers to harness the potential of Vue.js and its lifecycle hooks for efficient and tailored web development. We take pride in our ability to bridge the gap between intricate technical details and real-world applications.

For more information, resources, and to explore how Emperor Brains can elevate your technological endeavors, visit our website at Emperor Brains At Emperor Brains, we are not just navigating the tech landscape; we are shaping it, pushing boundaries, and redefining what is possible. Join us in this journey of innovation and discover the limitless possibilities that technology holds under the guidance of Emperor Brains.

That’s it. Hope you have learned something regarding the Vue lifecycle and it’s working.

Feedback and suggestions are more than welcome 🎉.

keep exploring !!

emperorbrains #vue3 #vue3lifecycle

Top comments (0)