Lifecycle hooks in Vue 3

Lifecycle hooks in Vue 3

In the modern programming world, creating web pages using HTML directly is not very effective. Rather people prefer Components to create HTML web pages. Because the components ease the development, performance and readability. We can divide the web pages into pieces of components. Each Component is responsible for its own business.

Lifecycle hooks in Vue 3

While we create components, we will go step by step procedure to fulfill its requirements. In Vue.js we can derive this as follows,

  1. Data observation
  2. template compilation
  3. mount the component instance to DOM
  4. update the DOM based on data

Between the steps, Vue.js provides a predefined function called Life Cycle Hooks. We can add our own logics by calling these life cycle hooks in between the component creations. It will be very helpful to know about Components in Vue3 before moving to this session. Let’s take the deep dive!

Lifecycle hooks in Vue 3

For Example, As per the component creation flow, the created hook will be called after the component instance is created.

Vue.createApp({
  data() {
    return { state: "hello to lifecycle hooks" }
  },
  created() {
    // `this` points to the vm instance
    console.log(this.state) // => hello to lifecycle hooks
  }
})

As shown above, we can use other hooks which are used to be called at different stages of component creation.

Options API vs Composition API

Above all, we can access lifecycle hooks in both options API and composition API. We have to invoke life cycle methods inside the setup function in the Composition API. Option API is available in both Vue.js 2 and 3 whereas composition API is available from Vue.js 3.

Options APIComposition API
beforeCreateNot needed* (directly write in setup)
createdNot needed*(directly write in setup)
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeUnmountonBeforeUnmount
unmountedonUnmounted
errorCapturedonErrorCaptured
renderTrackedonRenderTracked
renderTriggeredonRenderTriggered

Most importantly, beforeCreate and created are not available in composition API. However, we can write it’s logic directly in the setup function since setup is invoked around the created hook.

Note

In Optional API, all lifecycle hooks have this context bound to the instance. So we should not go for arrow functions (e.g. created: () => this.createdCallBack()) since arrow functions bind the parent context to this.

Lifecycle hooks – Options API

  • beforeCreate – called after the component instance has been initialized but before data observation.
  • created – called after the component instance has been created. Since instance is created we can set up data observation, computed properties, methods, watch/event callbacks. But we can not do DOM operation since the component is not mounted. The $el property is also not available yet.
  • beforeMount – called just before the component mounting process.
  • mounted – This is an important hook after created hook in the options API. mounted called after the component instance has been mounted. If the root component instance is mounted, then vm.$el will be there in the DOM. But it does not guarantee that all child components have also been mounted.
  • beforeUpdate – called at run time when data changes before the DOM is updated. It is a good place to remove manually added event listeners.
  • updated – called at runtime after the data changes and DOM patched.
  • beforeUnMount – called before a component instance is unmounted.
  • unmounted – called after a component instance has been unmounted.
  • errorCaptured – called when an error occurs from any child component.
  • renderTracked – called when virtual DOM rerender tracked.
  • renderTriggered – called when virtual DOM rerender triggered.

Lifecycle hooks Vue 3 Example

Life cycle hooks provide the ways to add their logic at specific stages while creating the components. Moreover in Vue.js 3, they are tree-shakable modules. You can import and use them in your composable logics.

import { onMounted } from "vue";

As shown above, we can get the lifecycle hooks  and use them in our logics at different stages. The full example for all lifecycle hooks shown below,

<template>
  <div>
    <button v-on:click="addToCart">Add to cart</button>
    <p>Cart{{ state }}</p>
  </div>
</template>

<script>
import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  onErrorCaptured,
  onRenderTracked,
  onRenderTriggered,
  ref,
} from "vue";

export default {
  setup() {
    onBeforeMount(() => {
      console.log("Component is onBeforeMount!");
    });
    onMounted(() => {
      console.log("Component is mounted!");
    });
    onBeforeUpdate(() => {
      console.log("Component is onBeforeUpdate!");
    });
    onUpdated(() => {
      console.log("Component is Updated!");
    });
    onBeforeUnmount(() => {
      console.log("Component is onBeforeUnmount!");
    });
    onUnmounted(() => {
      console.log("Component is un mounted!");
    });
    onErrorCaptured(() => {});
    onRenderTracked(({ key, target, type }) => {
      console.log("onRenderTriggered!")
      console.log({ key, target, type });
      /* This will be logged when component is rendered for the first time:
    {
      key: "cart",
      target: {
        cart: 0
      },
      type: "get"
    }
    */
    });
    onRenderTriggered(({ key, target, type }) => {
      console.log("onRenderTriggered!")
      console.log({ key, target, type });
      /* This will be logged when component is rendered for the first time:
    {
      key: "cart",
      target: {
        cart: 0
      },
      type: "get"
    }
    */
    });

    let state = ref(0);
    const addToCart = () => {
      state.value += 1;
    };
    return {
      state,
      addToCart,
    };
  },
};
</script>

<style scoped></style>

 

GitHub Link :

 

References :

  1. https://v3.vuejs.org/guide/instance.html#lifecycle-hooks
  2. https://v3.vuejs.org/api/options-lifecycle-hooks.html#lifecycle-hooks
  3. https://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html

Summary

In conclusion,

  • Firstly vue.js provides predefined function called Life Cycle Hooks.
  • Secondly we can access lifecycle hooks in both options API and composition API.
  • Life cycle hooks provide the way to add their logics at specific stages while creating the components.

Leave a Reply

%d bloggers like this: