11 Vue.js Lifecycle Hooks

Let’s understand how and when to use them with handy examples

Photo by Evie S. on Unsplash

Something that you absolutely need to know when you approach Vue.js for the first time is its Lifecycle Hooks.

You can go deep to start writing your JavaScript logic inside methods or computed properties and so on. Of course, I understand that when you are excited about learning a new technology you want to see it in action fast (I did exactly that btw ), but I guarantee you that understanding these Hooks will give you a strong foundation to learn this Javascript Framework.

If you get confused with methods and computed properties when you start with Vue.js, I suggest you read this article.

The Vue instance

The core of Vue.js is its instance. Every Vue application starts by creating one and it is an object that will help you to create your desired behavior.

The Vue instance contains different options[1]: data, props, template, methods, computed, watchers, lifecycles and much more.

As you can imagine the instance is the responsible for different things, for example setting data observation, compiling the template, mounting the instance to the DOM, updating the DOM when data changes and others. I invite you to read the documentation here if you are interested to know more about all these arguments.

The Vue lifecycle hooks

The lifecycle hooks are functions that give you the opportunity to add code at specific stages.

There are 11:

beforeCreate

create

beforeMount

mounted

beforeUpdate

updated

activated

deactivated

beforeDestroy

destroyed

errorCaptured

The beforeCreate, created, beforeMount, mounted and errorCaptured hooks will be executed automatically, all the others will be executed when something happens.

We will explore them one by one with examples so you can understand them without any doubts.

beforeCreate:

It is called immediately after the instance has been initialized and before that all the options[1] will be processed.

Called during server-side rendering

created:

It is called right after the instance has been created and after that all the options[1] have been set up.

Called during server-side rendering

beforeMount:

It is called right before the mounting of the DOM begins.

Called on the client-side

mounted:

It is called when the instance has been mounted and the el (the DOM) has been replaced.

Called on the client-side

beforeUpdate:

It is called when some data changes and before the DOM has been re-rendered.

Called on the client-side

updated:

It is called when some data changed and the DOM has been re-rendered.

Called on the client-side

activated:

This hook is used for <keep-alive> components (You can read more about it here), it allows you to know when a component inside the <keep-alive></keep-alive> tag is toggled ON.

Called on the client-side

deactivated:

This hook is used also for <keep-alive> components, it allows you to know when a component inside the <keep-alive></keep-alive> tag is toggled OFF.

Called on the client-side

beforeDestroy:

It is called right before the Vue instance is destroyed. At this stage the instance is still fully functional.

Called on the client-side

destroyed:

It is called after the Vue instance has been destroyed, this doesn’t mean that it will remove all the code from the DOM but that it will remove all the Java Script logic and the instance will not exist anymore.

Called on the client-side

errorCaptured:

This hook confused me in the beginning, also because the docs only says this:

Called when an error from any descendent component is captured. The hook receives three arguments: the error, the component instance that triggered the error, and a string containing information on where the error was captured. The hook can return false to stop the error from propagating further.

Based on my research, it is called by a “parent” component to handle an error from a “child” component. It is not accessible from the main instance but only from a component with children.

Let’s see the Vue lifecycle hooks in action

I know I said a lot of theoretical things so far but now it’s time to have some fun and to see them in action.

For better understanding I split the code into 3 sections. For every section, I will also give you the Codepens so you will be able to see the examples directly there or you can follow me with your text editor.

1. beforeCreate, created, beforeMount, mounted, beforeUpdate, updated Lifecycle Hooks

In your HTML write this:



<div id="app">

<h1>{{ title }}</h1>

<button

<button

</div> https://cdn.jsdelivr.net/npm/vue/dist/vue.js</a> "> {{ title }} @click ="title='New Title'">Update Title @click ="destroy()">Destroy

and in your JS:

new Vue({

el: '#app',

data: {

title: 'Hello Vue!',

},

beforeCreate: function() {

console.log("beforeCreate()")

},

created: function() {

console.log("created()")

},

beforeMount: function() {

console.log("beforeMount()");

},

mounted: function() {

setTimeout(function(){console.log("mounted()")}, 3000);

},

beforeUpdate: function() {

console.log("beforeUpdate()")

},

updated: function() {

console.log("updated()")

},

beforeDestroy: function() {

console.log("beforeDestroy()")

},

destroyed: function() {

console.log("destroyed()")

},

methods: {

destroy: function() {

this.$destroy();

}

}

})

If you open your console now you will be able to see all the console.log() and visually you can see when they are called.

I added a setTimeout inside the mounted to let you better understand that this function is called after the render of the DOM (You will see the title in the DOM and after the console.log() ).

To run the update and the destroy hooks just press the buttons.

Codepen here.

2. activated and deactivated Lifecycle Hooks

In your HTML write this:

and in your JS:

Vue.component('component1', {

data: function () {

return {

count: 0

}

},

activated: function() {

console.log("activated()")

},

deactivated: function() {

console.log("deactivate()")

},

template: '<h3>Template 1</h3>'

}) Vue.component('component2', {

data: function () {

return {

count: 0

}

},

template: '<h3>Template 2</h3>'

}) new Vue({

el: '#app',

data: {

selectedComponent: 'component2'

},

})

Here if you click the buttons you will be able to switch component and to see when these hooks are called.

Codepen here.

2. errorCaptured Lifecycle Hook Vue.js

In your HTML write this:

and in your JS:

Vue.component('componentparent', {

errorCaptured(err, vm, info) {

console.log("error:", err);

console.log("vm:", vm);

console.log("info:", info);

},

template:'<h3> Component parent<slot></slot> </h3>',

}) Vue.component('componentchild', {

template: '<h3> Template Child {{doesntexist()}} </h3>'

}) new Vue({

el: '#app',

})

Here you can see that the doesntexist() method doesn’t exist so you will get the error

Codepen here.

What about now?

The console.log() example made me understand very fast when they are called and how they work, and I hope it’s the same for you.

Now if you got them it’s up to you to understand how and when they can be useful during the development of your projects.