What is the Difference Between the Created and Mounted Hooks in Vue.js

Programmers are still struggling with the created and mounted hooks in Vue.js and trying to find out what is the difference between these two. Let’s figure out together and see which method is used for real-life situations covered up in this tutorial.

For the created() hook, after the processing of the options is finished, you can already have access to reactive data properties and change if necessary. At this stage of the process, DOM has not been mounted or added yet; thus, you cannot do any manipulation. The created() hook is used for fetching data from backend API and setting it to data properties. But in SSR, the mounted hook isn’t present and requires the performance of tasks like fetching data in created hook only.

The mounted() hook is called after the DOM has been mounted or rendered which enables you to have access to the DOM elements and you can perform DOM manipulation. Mounting hooks are often the most used ones. The best use case for the mounted hook is if you need to access or alter the DOM of your component immediately before or after the initial render.

To fetch any initial required data to be rendered from external API and assigning it to any reactive data properties, you can choose the created hook like this:

data:{
    myJson : null,
    errors: null
},
created(){
    //pseudo code
    database.get().then((res) => {
        this.myJson = res.data;
    }).catch((err) => {
        this.errors = err;
    });
}

Created and Mounted

Here are the definitions of these two hooks suggested by Vue.js documentation.

The created hook is called synchronously after the instance is created. At this stage, the instance has finished processing the options, which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.

The mounted hook is called after the instance has been mounted, where el 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.