Vue Lifecycle Diagram

Posted on  by admin

Lifecycle hooks are a window into how the library you are using works behind the scenes. Lifecycle hooks allow you to know when your component is created, added to the DOM, updated, or destroyed.

This article will introduce you to the creation, mounting, updating, and destruction hooks in Vue.js. To follow through this tutorial, you’ll need:.

Familiarity with Vue.js. Read the How To Develop Websites with Vue.js series to learn more. Creation hooks are the first hooks that run in your component.

They allow you to perform actions before your component has even been added to the DOM. Unlike any of the other hooks, creation hooks are also run during server-side rendering.

Use creation hooks if you need to set things up in your component, both during client rendering and server rendering.

Understanding Destruction Hooks (Teardown)

You will not have access to the DOM or the target mounting element (this.$el) inside of creation hooks. The beforeCreate hook runs at the initialization of your component - data has not been made reactive, and events have not been set up yet:.

In this example, when the beforeCreate hook is run, this snippet will log the message:. The created hook runs before the templates and Virtual DOM have been mounted or rendered - you are able to access reactive data and events that are active:.

  • In this example, the snippet will store property as Example property.

  • When the created hook is run, it will log a message:.

  • And then property is changed to Example property updated.

  • Later in the lifecycle,{{ propertyComputed }} will appear as Example property updated instead of Example property.

Conclusion

In this step, you reviewed some examples of creation hooks and are ready to move to the next part of the lifecycle, mounting hooks. Mounting hooks are often the most used hooks.

They allow you to access your component immediately before and after the first render. They do not, however, run during server-side rendering.

Introduction

Use mounting hooks if you need to access or modify the DOM of your component immediately before or after the initial render.

Do not use mounting hooks if you need to fetch some data for your component on initialization.

Other Hooks

Note: Use created (or created and activated for keep-alive components) for this instead. Especially if you need that data during server-side rendering.

Composition API

The beforeMount hook runs right before the initial render happens and after the template or render functions have been compiled:. In this example, when the beforeMount hook is run, this snippet will log the message:.

  • In the mounted hook, you will have full access to the reactive component, templates, and rendered DOM (via this.$el).

  • Use mounted for modifying the DOM—particularly when integrating non-Vue libraries:.

  • In this example, when the mounted hook is run, this snippet will log the message:.

  • In addition, a message of Example content. (this.$el.textContent) will be logged.

  • In this section, you explored use-cases for mounting hooks. In the next step, you review some examples that use updating hooks.

  • Updating hooks are called whenever a reactive property used by your component changes or something else causes it to re-render.

  • They allow you to hook into the watch-compute-render cycle for your component.

  • Use updating hooks if you need to know when your component re-renders, perhaps for debugging or profiling.

  • Do not use updating hooks if you need to know when a reactive property on your component changes.

Use computed properties or watchers for that instead. The beforeUpdate hook runs after data changes on your component and the update cycle begins, right before the DOM is patched and re-rendered.

Composition API

Understanding Updating Hooks (Diff and Re-render)

Use beforeUpdate if you need to get the new state of any reactive data on your component before it gets rendered:. First, this snippet will store counter as 0. When the created hook is run, it will increment counter every 1000 ms.

  • When the beforeUpdate hook is run, this snippet will log the message:.

  • And a number for counter is also logged. The updated hook runs after data changes on your component and the DOM re-renders.

  • Use updated if you need to access the DOM after a property change:.

  • First, this snippet will store counter as 0. When the created hook is run, it will increment counter every 1000 ms.

  • When the updated hook is run, this snippet will log the message:.

  • And a boolean value of true is logged because the rendered value and current value are equal.

  • Now that you’ve explored the use of updating hooks, you are ready to learn about destruction hooks.

  • Destruction hooks allow you to perform actions when your component is destroyed, such as cleanup or analytics sending.

  • They fire when your component is being torn down and removed from the DOM.

Understanding Mounting Hooks (DOM Insertion)

beforeDestroy is fired right before teardown.

  • Your component will still be fully present and functional.

  • Use beforeDestroy if you need to clean up events or reactive subscriptions:.

This snippet will first store exampleLeakyProperty. When the beforeDestroy hook is run, this snippet will log the message:. And then exampleLeakyProperty is deleted.

Understanding Creation Hooks (Initialization)

By the time you reach the destroyed hook, there’s practically nothing left on your component.

Prerequisites

Everything that was attached to it has been destroyed. Use destroyed if you need to do any last-minute cleanup or inform a remote server that the component was destroyed:.

First, this snippet will import ExampleAnalyticsService.

Options API

When the beforeDestroy hook is run, this snippet will log the message:. What remains of the component will be logged to console, and ExampleAnalyticsService will be passed the message Component destroyed..

With that, you have completed your general review of the Vue.js lifecycle hooks. There are two other hooks, activated and deactivated. These are for keep-alive components, a topic that is outside the scope of this article.

Suffice it to say that they allow you to detect when a component that is wrapped in a tag is toggled on or off. You might use them to fetch data for your component or handle state changes, effectively behaving as created and beforeDestroy without the need to do a full component rebuild.

created() – Options API

In this article, you were introduced to different lifecycle hooks available in the Vue.js Instance Lifecycle. You explored the different use cases for creation hooks, mounting hooks, updating hooks, and destruction hooks.

Options API

If you’d like to learn more about Vue.js, check out our Vue.js topic page for exercises and programming projects.

Modified1 year, 7 months ago. I'm going through the official documentation of Vue.js and found this diagram about different stages and steps in a Vue instance's lifecycle.

I understand the basic features of Vue but I am unable to understand the meaning of many stages mentioned in the diagram. For example, "Compile template into render function" or "Virtual DOM re-render and patch".

What about the Composition API Creation Hooks?

I have no idea what they mean. I know it says in the documentation that you don’t need to fully understand everything right now, but I was hoping if some Vue(or frontend) expert could briefly explain these steps in simple language. 11 gold badge77 silver badges2020 bronze badges.

2020 bronze badges. It can all be a little overwhelming, here's what those things are.

Composition API

Mounting Hooks – Accessing the DOM

Render Functions. When Vue compiles your Vue instance, it creates a render function, which is a pure JavaScript representation of your HTML.

beforeMount() and onBeforeMount()

Something like this:. Will actually turn into something like this:. Here's a JSFiddle: https://jsfiddle.net/bvvbmpLo/. You don't need to handle that, Vue does it for you, and most of the time you won't find yourself writing render functions. However, it is important to understand that Vue is doing some behind the scenes work to represent your templates in pure JavaScript.

Options API

Virtual DOM re-render and patch. You really don't need to know about this, but Vue uses a virtual DOM, because it's is easier to track changes and decide which parts of the DOM need updating.

Composition API

In reality, what happens is that Vue builds up a tree that represents the DOM (called a vTree), then when you change state it uses something called a diffing algorithm which compares the previous vTree to the current vTree as it now stands, and attempts to figure out which part of the page it needs to change to reflect that state in your view.

The changing of a small part of your page to represent the new state is called patching.

That's a pretty high-level overview of a virtual DOM, it's fiendishly complex to get this working efficiently which is why frameworks like Vue exist in the first place. If you're interested in learning more about that then try taking a look at Matt-Esch/virtual-dom on Github, which does a great job of explaining this concept in more detail.

mounted() and onMounted()

55 gold badges5858 silver badges6767 bronze badges.

6767 bronze badges.

Update Hooks – Reactivity in the VueJS Lifecycle

The updated lifecycle event is triggered whenever reactive data is modified, triggering a render update.

beforeUpdate() and onBeforeUpdate()

Runs when the data is changed, but before the component is re-rendered. This is a good place to update the DOM manually before any changes happen. For example, you can remove event listeners.

beforeUpdate could be useful for tracking the number of edits made to a component or even tracking the actions to create an “undo” feature.

updated() and onUpdated()

The updated methods call once the DOM has been updated. Here’s some starter code that uses both beforeUpdate and updated.

Vue Template

With either of the corresponding scripts.

Options API

OR

Composition API

These methods are useful, but for a lot of use cases we may want to consider using watchers to detect these data changes instead. Watchers are good because they give the old value and the new value of the changed data.

Another option is using computed values to change the state based on elements.

Destruction Hooks – Cleaning Things Up

The destruction hooks for a component are used in the process of removing a component and cleaning up all the loose ends. This is the time for removing event listeners and things that could lead to memory leaks if not properly processed.

beforeUnmount() and onBeforeUnmounted()

Because this is before the component starts to get torn down, this is the time to do most, if not all, of the clean up. At this stage, your component is still fully functional and nothing has been destroyed yet.

An example of removing an event listener would look like this in the Options API.

Options API

And this in the Composition API

Composition API

One way to see this in action is to work in Vite, vue-cli, or any dev environment that supports hot reloading. When your code updates, some of your components will unmount and mount themselves..

unmounted() and onUnmounted()

At this point, most of your component and its properties are gone so there’s not much you can do. Once again, I’d use print out some data to see what exactly is still around and if it could be useful for your project.

Activation Hooks – Managing Keep-Alive Components

A keep-alive tag is a wrapper element for dynamic components. It stores a cached reference to inactive components so that Vue does not have to create an entirely new instance every time a dynamic component changes.

For this specific use case, Vue gives us two lifecycle hooks

activated() and onActivated()

This method is called whenever a kept-alive dynamic component is “reactivated” – meaning that it is now the active view of the dynamic component.

For example, if we are using keep-alive components to manage different tab views, every time we toggle between tabs, the current tab will run this activated hook.

Let’s say we have the following dynamic component setup using the keep-alive wrapper.

Composition API

Inside our Tab1.vue component, we can access our activation hook like this.

Composition API

deactivated() and onDeactivated()

As you may guess, this is called when a kept alive component is no longer the active view of a dynamic component.

This hook can be useful for use cases like saving user data when a specific view loses focus and triggering animations.

We can capture the hook like this.

Composition API

Now, when we toggle between the tabs – each dynamic component’s state will be cached and saved.

Great!

Vue 3 Debug Hooks

Vue 3 gives us two hooks that we can use for debugging purposes. They are:

  • onRenderTracked

  • onRenderTriggered

Both of these events take a DebuggerEvent that allows us to tell what is causing a re-render in our Vue instance.

Conclusion

Whether you decide to use the Options API or the Composition API, it’s important to know not only what lifecycle hook to use, but why you’re using it.

For many problems, multiple lifecycle hooks can work. But it’s good to know which is the best for your use case. No matter what, you should just think about it and have a good reason for choosing a specific lifecycle hook.

I hope this helped you understand a little bit more about lifecycle hooks and how to implement them in your projects.

Happy coding!