Loading...

VueJS Lifecycle Hooks


in this tutorial we are going to learn what are vuejs lifecycle hooks ? why we use them in vuejs ?

What are VueJS Lifecycle Hooks ?


first of all understands what is a lifecycle ? as the name suggest it means in vuejs that an app (vue instance) is going through the initializion phase to the working phase then finally to the destruction phase.
VueJs lifecycle hooks are basically events (or you can say as methods) provided by core VueJs team to handle the lifecycle of a vue instance in VueJs App as per your needs.

for controlling the lifecycle of a vue instance the core vuejs team gives us 8 hooks for handling 4 lifecycle stages ( 2 hooks for each stage ).
these four lifecycle stages of an vue instance are :

1. creation stage (you can better understands as this an initialization phase of an app).
core vuejs team here gives us two hooks (methods) to handle and control the vue instance here are:
beforeCreate() method and created() method.

2. mount stage ( it comes when a vue instance is initilized and ready to mount in the app space).
core vuejs team here gives us two hooks (methods) to handle and control the vue instance here are:
beforeMount() method and mounted() method.

3. updation stage ( it comes when a vue instance needs to change its state based on user interactivity).
core vuejs team here gives us two hooks (methods) to handle and control the vue instance here are:
beforeUpdate() method and updated() method.

4. destroy stage ( it comes when a vue instance is going to shut down its working.).
core vuejs team here gives us two hooks (methods) to handle and control the vue instance here are:
beforeDestroy() method and destroyed() method.

for more information you can go through the below figure from the official vuejs website.
vuejs-lifecycle-hooks
figure source    https://vuejs.org.
in the above figure it is clear that after call creted hook vue instance checks that el option (use to connect vue instance with DOM) is available or not.
- if available then check its template components.
- if not then called vue instance default $mounted method. then checks its template components.

beforeCreate()


this hook is called just after when a new vue instance is instantiated and before the initialization of the vue instance data, methods, computed etc.
in other means it is executed in the vue instance just before data and methods initialization.
in this method you can not use vue instance (data and methods) because all these are not available to use at that time.
it is basically used when the app is loading to display greeting message etc.
for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    message : 'welcome to our vue store',
  },
  beforeCreate(){
    console.log("please wait the app is loading ...");
  },
  computed:{
    msg: function(){
      console.log(this.message);
    } 
  }  

})

output:

please wait the app is loading ...

        		     					    		
        		     					    	

created()


in vue this hook is used after the initialization of the data, methods and computed etc in the vue instance.
this hook is just called after the beforeCreate() hook.
becasuse the data and methods are available in vue instance. you can now perform operations on data, methods and hooks in this hook.
you can fetch data from json api, database in this stage and assign to the data in it.
for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    message : 'welcome to our vue store.',
  },
  beforeCreate(){
    console.log("please wait the app is loading ...");
  },
  created(){
  	this.msg;
  },
  computed:{
    msg: function(){
      console.log(this.message);
    } 
  }  

})

output:

please wait the app is loading ...

welcome to our vue store.
        		     					    		
        		     					    	

beforeMount()


in vue this hook is called just after the created() hook.
you can use this hook to perform operations which is required to be performed just before app is going live
this hook is called before the app is going in the app space (mounting on the DOM).
in this lifecycle phase the vue instance doesn't have access to the 'el' at this point of time.
for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    message : 'welcome to our vue store.',
  },
  beforeCreate(){
    console.log("please wait the app is loading ...");
  },
  created(){
  	this.msg;
  },
  beforeMount(){
  	console.log('still waiting to connected to the DOM ');
  },
  computed:{
    msg: function(){
      console.log(this.message);
    } 
  }  

})

output:

please wait the app is loading ...

welcome to our vue store.

still waiting to connected to the DOM
        		     					    		
        		     					    	

mounted()


in vue this hook is called after the vue instance is connected to the DOM.
now the vue instance have access to the dom elements then here we interacts with the user directly and renders both the parent and child component templates.
for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    message : 'welcome to our vue store.',
  },
  beforeCreate(){
    console.log("please wait the app is loading ...");
  },
  created(){
  	this.msg;
  },
  beforeMount(){
  	console.log('still waiting to connected to the DOM ');
  },
  mounted(){
  	console.log('now ready to interact with user.')
  },
  computed:{
    msg: function(){
      console.log(this.message);
    } 
  }  

})

output:

please wait the app is loading ...

welcome to our vue store.

still waiting to connected to the DOM

now ready to interact with user.
        		     					    		
        		     					    	

beforeUpdate()


in vue this hook is called when the user interacts with the dom to update value or some changes which is in the form of click like add to product in cart to update the cart etc.
in this hook you can perform checks before update the data which reflects in the dom (as a result of re-render dom).

for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    product: '',
    message : 'welcome to our vue store.',
  },
  beforeCreate(){
    console.log("please wait the app is loading ...");
  },
  created(){
    this.msg;
  },
  beforeMount(){
    console.log('still waiting to connected to the DOM ');
  },
  mounted(){
    console.log('now ready to interact with user.');
  },
  beforeUpdate(){
    this.addProduct('iphone 11 pro');
  },
  methods: {
    addProduct: function(item){
      this.product = item;
      console.log('user requested to : add ' + this.product + ' in cart ');
    }
  },
  computed: {
    msg: function(){
      console.log(this.message);
    } 
  }  

})

output:

please wait the app is loading ...

welcome to our vue store.

still waiting to connected to the DOM

now ready to interact with user.

user requested to : add iphone 11 pro in cart
        		     					    		
        		     					    	

updated()


in vue this hook is called after the beforeUpdate() hook.
in this hook dom is re-render based on the request of updation. in this hook state of the data is changed.
and when the data changes its value then vue reactive system here update the dom here.
for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    product: '',
    message : 'welcome to our vue store.',
  },
  beforeCreate(){
    console.log("please wait the app is loading ...");
  },
  created(){
    this.msg;
  },
  beforeMount(){
    console.log('still waiting to connected to the DOM ');
  },
  mounted(){
    console.log('now ready to interact with user.');
  },
  beforeUpdate(){
    this.addProduct('iphone 11 pro');
  },
  updated(){
  	console.log('finally ' + this.product + ' is added in cart');
  },
  methods: {
    addProduct: function(item){
      this.product = item;
      console.log('user requested to : add ' + this.product + ' in cart ');
    }
  },
  computed: {
    msg: function(){
      console.log(this.message);
    } 
  }  

})

output:

please wait the app is loading ...

welcome to our vue store.

still waiting to connected to the DOM

now ready to interact with user.

user requested to : add iphone 11 pro in cart

finally iphone 11 pro is added in cart
        		     					    		
        		     					    	

beforeDestroy()


in vue this hook is used when vue instance is going to stops it working.
it is basically used to free up the memory occupies by the vue instance in the system.
it works just like destructor() function works in many programming languages
for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    product: 'iphone 11 pro',
    message : 'welcome to our vue store.',
  },
  beforeDestroy(){
  	this.freeSpace();
  },
  methods: {
    freeSpace: function(item){
      this.product = '';
      this.message = '';
      delete this.product;
      delete this.message;
      console.log(' free the memory space ');
    }
  },
  computed: {
    msg: function(){
      console.log(this.message);
    } 
  }  

})

output:

free the memory space

        		     					    		
        		     					    	

destroy()


in vue this is the final hook and performs the final task for the vue instance.
it is used to destroy the vue instance and unmount to the dom.
default $destroy() method of vue instance is used to destroy the vue instance here
for example :
        		     					    		
var vm = new Vue({
  el: '#app',
  data: {
    product: 'iphone 11 pro',
    message : 'welcome to our vue store.',
  },
  destroy(){
  	this.$destroy();
  	console.log(this);
  },
  methods: {
    freeSpace: function(item){
      this.product = '';
      this.message = '';
      delete this.product;
      delete this.message;
      console.log(' free the memory space ');
    }
  },
  computed: {
    msg: function(){
      console.log(this.message);
    } 
  }  

})