Vue Lifecycle Hooks

Vue Lifecycle Hooks

Every Vue component goes through a series of initialization steps when it is created.

It sets up data observation, compiles the template, mounts the instance to the DOM, and eventually destroys itself.

Vue provides "Lifecycle Hooks", which allow you to execute custom code at these specific stages.


The Component Lifecycle

There are several major stages in a Vue component's life.

The most commonly used hooks are:


Using the mounted() Hook

The mounted() hook is incredibly popular.

It is the perfect place to fetch data from an API, because you know the HTML is ready for the user to see.

It is also the correct place to initialize any third-party JavaScript libraries (like a map or chart).

Mounted Hook Example:

export default {
  data() {
    return { status: 'Loading...' }
  },
  mounted() {
    // This fires immediately when the component hits the screen!
    this.status = 'Component is fully mounted!';
    console.log('The component is now on the screen.');
  }
}

Using the updated() Hook

The updated() hook is called after data changes cause the virtual DOM to re-render and patch.

If you need to access the DOM after a state change, this is where you do it.

However, you must be careful not to change the state inside this hook, or you will cause an infinite loop!

Updated Hook Example:

export default {
  updated() {
    console.log('The DOM has just been updated with new data!');
  }
}

Lifecycle Hooks in Composition API

If you are using the modern <script setup>, the syntax for lifecycle hooks changes slightly.

You must import them from the vue library and prefix them with on.

For example, mounted() becomes onMounted().


Exercise 1 of 2

?

Which lifecycle hook is the best place to make an initial API fetch request?

Exercise 2 of 2

?

What is a major risk of modifying reactive data inside the updated() hook?