Appearance
What is the Difference Between the Created and Mounted Hooks in Vue.js
Programmers often struggle with the created and mounted hooks in Vue.js and try to find the difference between them. Let’s figure out together which method is used for real-life situations covered in this tutorial.
For the created() hook, after the processing of the options is finished, you already have access to reactive data properties and can modify them as needed. At this stage, the DOM has not been mounted yet; thus, you cannot perform any DOM manipulation. The created() hook is used for fetching data from a backend API and setting it to data properties. In SSR, the mounted hook is not available, so tasks like data fetching must be performed in the created hook only.
The mounted() hook is called after the DOM has been mounted or rendered, which enables you to access DOM elements and perform DOM manipulation. The mounted hook is often the most used. The best use case for the mounted hook is if you need to access or alter the DOM of your component strictly after the initial render.
To fetch any initial required data to be rendered from an external API and assign it to reactive data properties, you can choose the created hook like this:
Vue.js created hook
js
export default {
data() {
return {
myJson: null,
errors: null
}
},
created() {
fetch('/api/data')
.then((res) => res.json())
.then((data) => {
this.myJson = data;
})
.catch((err) => {
this.errors = err;
});
}
}Note: Vue 2 reached end-of-life in December 2023. In Vue 3, these lifecycle hooks are typically handled in the setup() function using onBeforeMount and onMounted.
Created and Mounted
Here are the definitions of these two hooks from the Vue.js (Vue 2) documentation.
The created (Vue 2) 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 (Vue 2) hook is called after the instance has been mounted, where the root element 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.
| Feature | created | mounted |
|---|---|---|
| DOM Access | Not available ($el is undefined) | Available ($el is populated) |
| SSR Compatibility | Supported | Not supported (browser-only) |
| Primary Use Case | Data fetching, API calls | DOM manipulation, third-party integrations |