What Are Lifecycle Hooks In Vuejs And How Do They Work?

There are times where you want to add your own code at specific stages of your app.
by your own code, I mean that you will be able to trigger events, call functions, etc.
and by specific stages of your app, I mean your Vue app’s different instance stages
such as ( when the instance is created, or before it is mounted or when it is updated, or before it is updated…etc).
here is a diagram of how lifeCycle hooks work in VueJs:


Example:

export default {
   data(){},
   updated() {
     this.$nextTick(function () {
       // this code is only executed after the entire view has been re-rendered
     })
   }
}

note: it is not declared within methods. and methods can be defined within it.
in the example above the hook is not called during server-side rendering., but only the frontend rendering.
the Hook “updated” will be called after a data change causes the virtual DOM to be re-rendered and patched.
it works just like watching data changes but this time, watching your entire Vue app for any changes. want to know about watching data and prop changes in Vuejs visit this topic: https://stopbyte.com/t/how-to-watch-nested-props-and-data-in-vuejs.

now let’s see all LifeCycle hooks are there in Vue.js:

1- beforeCreate:

everything defined within this Function will be Called synchronously after the instance has been initialized, but before data observation and event/watcher have been setup.
example:

beforeCreate() {
     // Code that will run only after instance initialization
   })
}

2-created:

everything defined within this Function will be Executed synchronously after the instance is created.
meaning after all these topics have been set: "computed properties", "methods" and "watch/event" callbacks.
However, the instance is not yet Mounted, and the $el property will not be available yet.
example:

created() {
     // Code that will run after instance is created but not yet mounted
   })
}

3-beforeMount:

this hook is called right before the mounting “above” begins: the render function is about to be called for the first time.

Please note: This hook is not called during server-side rendering.
example:

beforeMount() {
    // Code that will run right before the mounting/redering begins

4-mounted:

this hook called after the instance is mounted, where element, passed to Vue.createApp({}).mount() is replaced by the newly created vm.$el . If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.
note:
mounted does not guarantee that all child components have also been mounted.
so in case you wanted to wait until the entire view has been rendered, you can use vm.$nextTick inside of your mounted lifecycle hook.

Example:
with waiting till child components are mounted as well

mounted() {
  this.$nextTick(function () {
    // Code that will run only after the
    // entire view has been rendered
  })
}

This hook is not called during server-side rendering.

5-beforeUpdate:

this hook is called when data changes and before the DOM is patched.
it is very convenient if you want to access the existing DOM before an update, e.g. to remove manually added event listeners.

  • This hook is not called during server-side rendering, because only the initial render is performed server-side.
    Example:
beforeUpdate() {
    // code to be called before DOM is updated.
  })
}

6-updated:

this one is called after a data change causes the virtual DOM to be updated(re-rendered and patched).
At this point the component’s DOM will have been updated, so you will be able to perform DOM-dependent operations here. However, in most cases, you should avoid changing the state inside the hook. To react to state changes, it’s usually better to use a computed or watchers.
Note: updated just like the “mounted” hook, does not guarantee that all child components have also been re-rendered. If you want to wait until the entire view has been re-rendered, you can use vm.$nextTick]inside of your hook.

updated() {
  this.$nextTick(function () {
    // Code that will run only after the
    // entire view has been re-rendered
  })
}

This hook is not called during server-side rendering.

7-activated:

this one is called when a kept-alive dynamic component is activated.

This hook is not called during server-side rendering.

8-deactivated:

this is called when a kept-alive component is deactivated.

This hook is not called during server-side rendering.

9-beforeUnmount:

Called right before a component instance is unmounted. At this stage, the instance is still fully functional.

This hook is not called during server-side rendering.

10-unmounted:

this one is called after a component instance has been unmounted. When this hook is called, all directives of the component instance have been unbound, all event listeners have been removed, and all child component instances have also been unmounted.
This hook is not called during server-side rendering.

11-errorCaptured:

As the name suggests it is called whenever an error from any descendent component is captured.
This hook receives three arguments: the error, the component instance that triggered the error, and a string containing information on where the error was captured.
To stop the error from propagating further the hook can return false.
notes:

  • You can modify component state in this hook. However, it is important to have conditionals in your template or render function that short circuits other content when an error has been captured; otherwise the component will be thrown into an infinite render loop.
  • By default, all errors are still sent to the global config.errorHandler if it is defined, so that these errors can still be reported to an analytics service in a single place.
  • If multiple errorCaptured hooks exist on a component’s inheritance chain or parent chain, all of them will be invoked on the same error.
  • If the errorCaptured hook itself throws an error, both this error and the original captured error are sent to the global config.errorHandler.
  • An errorCaptured hook can return false to prevent the error from propagating further. This is essentially saying “this error has been handled and should be ignored.” It will prevent any additional errorCaptured hooks or the global config.errorHandler from being invoked for this error.

12-renderTracked

it’s called when virtual DOM re-render is tracked. The hook receives a debugger event as an argument. This event tells you what operation tracked the component and the target object and key of that operation.

Example:

#html
<div id="app">
  <button v-on:click="addToCart">Add to cart</button>
  <p>Cart({{ cart }})</p>
</div>
#js
const app = Vue.createApp({
  data() {
    return {
      cart: 0
    }
  },
  renderTracked({ key, target, type }) {
    console.log({ key, target, type })
    /* This will be logged when component is rendered for the first time:
    {
      key: "cart",
      target: {
        cart: 0
      },
      type: "get"
    }
    */
  },
  methods: {
    addToCart() {
      this.cart += 1
    }
  }
})

app.mount('#app')

13-renderTriggered:

Called when virtual DOM re-render is triggered.Similarly to renderTracked , receives a debugger event as an argument. This event tells you what operation triggered the re-rendering and the target object and key of that operation.

Example:

<div id="app">
  <button v-on:click="addToCart">Add to cart</button>
  <p>Cart({{ cart }})</p>
</div>
const app = Vue.createApp({
  data() {
    return {
      cart: 0
    }
  },
  renderTriggered({ key, target, type }) {
    console.log({ key, target, type })
  },
  methods: {
    addToCart() {
      this.cart += 1
      /* This will cause renderTriggered call
        {
          key: "cart",
          target: {
            cart: 1
          },
          type: "set"
        }
      */
    }
  }
})

app.mount('#app')
1 Like