Overview of Lifcycle Hooks
Get introduced to the two Vue lifecycle hooks.
We'll cover the following
In the first chapter of this course, we’ll look into lifecycle hooks. They are methods called automatically for every component throughout its various stages of existence. They can execute logic upfront or during cleanup and allow for a rich experience.
A component’s life
Generally, we divide a component’s life into three phases:
- Initialization: This involves setting up the component and rendering the template.
- Lifetime: This is where the user can interact with the component/app.
- Teardown: This involves removing the template and ending the instance.
Each of these phases has a collection of lifecycle hooks. In the initialization and teardown phases, these hooks have very defined points when they happen. In contrast, a hook can be executed at any time, sometimes even multiple times during a component’s lifetime. Let’s first look at the initialization phase.
Initialization of a component
The following challenge is for us to see what we already understand about lifecycle hooks. Try to bring the different steps of a component’s initialization in the correct order.
The setup hooks allow us to precisely target specific spots in the process and, therefore, will enable us to fine-tune the behavior of our app. However, these possibilities also bear some danger—using the wrong hooks for some logic may impact performance or usability. The same is true for the teardown process.
Teardown of a component
The teardown process describes what Vue is doing while removing a component. Various actions can result in Vue removing a component, but most behave the same. Of course, there are exceptions, like <keep-alive>
.
We will now repeat the exercise we did before for the teardown process. Try to bring the different steps of a components initialisation in the correct order:
We’ve now covered the first and the last phase of a component’s life. These two phases are executed automatically and are, only up to a certain extent, caused by the user. Setup happens on rendering, and teardown happens whenever a component isn’t necessary anymore. There is yet another phase, though— one in which a component interacts with the user.
Lifetime of a component
There are also some lifecycle hooks while the component is active and used. For example, beforeUpdate
and updated
hooks get called whenever the DOM is updated, and the activated
and deactivated
hooks play together with the <keep-alive>
hook.
The critical difference between update hooks and all other hooks is that update hooks may be triggered at any time. That’s because it depends on the interaction and the component’s behavior.