Which VueJS lifecycle hook must Asynchronous HTTP requests be called in?

TL;DR in the general (and safe) case, use created().

Vue’s initialization code is executed synchronously.

Technically, any ASYNChronous code you run in beforeCreate(), created(), beforeMount() will only respond after all of those hooks finish. See demo:

new Vue({
  el: '#app',
  beforeCreate() {
    setTimeout(() => { console.log('fastest asynchronous code ever') }, 0);
    console.log('beforeCreate hook done');
  },
  created() {
    console.log('created hook done');
  },
  beforeMount() {
    console.log('beforeMount hook done');
  },
  mounted() {
    console.log('mounted hook done');
  }
})
<script src="https://unpkg.com/vue@2/dist/vue.min.js"></script>
<div id="app">
  Check the console.
</div>

In other words, if you make an Ajax call in beforeCreate(), no matter how fast the API responds, the response will only be processed way later, way after the created() has been executed.

What should guide your decision, then?

  • Need just to trigger a call as soon as possible?
    • Use beforeCreate()
    • Why?
      • It runs sooner than any of those hooks, but…
  • Need to read from or modify data right away?
    • Use created()
    • Why?
      • State is only initialized between beforeCreate() and created(), so if you assign some data before created(), it would be lost.
  • Need anything that is generated after created()?
    • Use beforeMount()
    • Why?
      • I don’t know anything that isn’t available at created() and is available at beforeMount() other than the compiled this.$options.render render function (see source as well), so this case must really be a rare situation.

Leave a Comment