Vue Lifecycle Hooks
In Vue, lifecycle hooks are certain points in a component’s lifecycle where we can add code to perform specific tasks.
Lifecycle Hooks
A certain function is called upon each time a component enters a new phase of its lifecycle, and we have the ability to add code to that method. Lifecycle hooks are functions that allow us to “hook” our code into a specific step of the process.
All of a component’s lifecycle hooks are as follows:
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeUnmount
- unmounted
- errorCaptured
- renderTracked
- renderTriggered
- activated
- deactivated
- serverPrefetch
Here are some illustrations of these lifecycle hooks.
The 'beforeCreate' Hook
Before the component is initialized, or before Vue has set up the component’s data, computed properties, methods, and event listeners, the beforeCreate lifecycle hook takes place.
For example, we can use the beforeCreate hook to set up a global event listener. However, since data, watchers, and methods are not yet generated, we should refrain from attempting to access component items via the beforeCreate lifecycle hook.
Furthermore, since DOM elements are not formed until after the component is mounted, attempting to access them from the beforeCreate lifecycle hook is illogical.
Example
CompOne.vue:
Component
This is the component
{{ text }}
App.vue:
The 'beforeCreate' Lifecycle Hook
We can see the console.log() message from 'beforeCreate' lifecycle hook, but there is no effect from the text change we try to do to the Vue data property, because the Vue data property is not created yet.
Line 15 of CompOne.vue in the example above has no effect since it tries to modify the text inside a Vue data property, even though the property hasn’t been created yet. Additionally, don’t forget to view the output of the console.log() call on line 16 by opening the browser console.
The 'created' Hook
Vue has already set up the component’s data, computed properties, methods, and event listeners before the created lifecycle hook occurs.
Since DOM elements cannot be accessed before the component is mounted, we should refrain from attempting to access them from the created lifecycle hook.
You may put up initial data values or retrieve data using HTTP requests by using the created lifecycle hook. The initial value of the data property ‘text’ is set as follows:
Example
CompOne.vue:
Component
This is the component
{{ text }}
App.vue:
The 'created' Lifecycle Hook
We can see the console.log() message from 'created' lifecycle hook, and the text change we try to do to the Vue data property works, because the Vue data property is already created at this stage.
The 'beforeMount' Hook
Just before to the component being mounted and so added to the DOM, the beforeMount lifecycle hook takes place.
Since DOM elements cannot be accessed before the component is mounted, we should refrain from attempting to access them from the beforeMount lifecycle hook.
As can be seen in the example below, line 11 in CompOne.vue is broken and causes an error to appear in the browser console. We are still unable to access DOM elements within the component.
Example
CompOne.vue:
Component
This is the component
We try to access this text from the 'beforeMount' hook.
App.vue:
The 'beforeMount' Lifecycle Hook
We can see the console.log() message from the 'beforeMount' lifecycle hook, but the text change we try to do to the 'pEl' paragraph DOM element does not work, because the 'pEl' paragraph DOM element does not exist yet at this stage.
The 'mounted' Hook
We may add our logic to the mounted() function, which is run immediately after a component is added to the DOM tree.
This is the first opportunity we have to perform operations on DOM elements that are part of the component, such as using the $refs object and the ref attribute, as we do in the second example down below.
Example
CompOne.vue:
Component
Right after this component is added to the DOM, the mounted() function is called and we can add code to that mounted() function. In this example, an alert popup box appears after this component is mounted.
Note: The reason that the alert is visible before the component is visible is because the alert is called before the browser gets to render the component to the screen.
App.vue:
The 'mounted' Lifecycle Hook
Note: In the example above, the alert() is visible PRIOR to the component; however, the mounted stage occurs AFTER the component is placed to the DOM. The reason for this is because the component is first added to the DOM, but the mounted stage occurs and the alert() becomes visible, pausing the browser’s rendering of the component before it can be rendered on the screen.
Here’s an illustration that might be more helpful: to mount the form component and place the cursor inside the input field so that the user can begin typing.
Example
CompOne.vue:
Form Component
When this component is added to the DOM tree, the mounted() function is called, and we put the cursor inside the input element.
(This form does not work, it is only here to show the mounted lifecycle hook.)
The 'beforeUpdate' Hook
Every time there is a modification to our component’s data, but before the update is displayed on the screen, the beforeUpdate lifecycle hook is triggered. The updated lifecycle hook is immediately preceded by the beforeUpdate lifecycle hook.
One unique feature of the beforeUpdate hook is that it allows us to make changes to the application without causing a fresh update, which helps us avoid the otherwise never-ending loop. This is the rationale behind not making any modifications to the application using the updated lifecycle hook, as doing so will result in the creation of an infinite loop. Just glance at the red-colored third example from below.
Example
To show that the beforeUpdate() function has run, the beforeUpdate() function appends a <li> tag to the document.
CompOne.vue:
Component
This is the component
App.vue:
The 'beforeUpdate' Lifecycle Hook
Whenever there is a change in our page, the application is 'updated' and the 'beforeUpdate' hook happens just before that.
It is safe to modify our page in the 'beforeUpdate' hook like we do here, but if we modify our page in the 'updated' hook, we will generate an infinite loop.
The 'updated' Hook
Our component updates its DOM tree before calling the updated lifecycle hook.
Example
Using console.log(), the updated() function generates a message. This occurs each time the page is modified—in this case, each time a component is added or withdrawn.
CompOne.vue:
Component
This is the component
App.vue:
The 'updated' Lifecycle Hook
Whenever there is a change in our page, the application is updated and the updated() function is called. In this example we use console.log() in the updated() function that runs when our application is updated.
After ten clicks on the “Add/Remove Component” button, the outcome is visible in the browser console:
Note: When the updated lifecycle hook is invoked, we have to be careful not to change the page itself since this will cause the page to update infinitely.
Let’s try what happens if we follow the advice in the following remark exactly. Will there be continuous page updates?
Example
The updated() function adds text to a paragraph, which causes the page to be updated once again. This process repeats endlessly. Fortunately, your browser will eventually break this loop.
CompOne.vue:
Component
This is the component
App.vue:
The 'updated' Lifecycle Hook
Whenever there is a change in our page, the application is updated and the updated() function is called.
The first change that causes the updated hook to be called is when we remove the component by clicking the button. When this happens, the update() function adds text to the last paragraph, which in turn updates the page again and again.
{{ text }}
This is the console warning that appears in the Chrome browser when you execute the code above locally in dev mode on your computer:
The 'beforeUnmount' Hook
Shortly before a component is deleted from the DOM, the beforeUnmount lifecycle hook is invoked.
The example below shows that the beforeUnmount hook still allows us to access component elements in the DOM.
Example
CompOne.vue:
Component
Strawberries!
App.vue:
Lifecycle Hooks
The 'unmounted' Hook
A component’s removal from the DOM triggers the calling of the unmounted lifecycle hook.
For instance, you can use this hook to eliminate event listeners and stop timers or intervals.
The unmounted() function is invoked when a component is unmounted, and we may add our code to it:
Example
CompOne.vue:
Component
When this component is removed from the DOM tree, the unmounted() function is called and we can add code to that function. In this example we create an alert popup box when this component is removed.
App.vue:
Lifecycle Hooks
Note: In the example above, the alert() is shown PRIOR to the component disappearing, but the unmounted stage occurs AFTER the component is gone from the DOM. This is because, although the component is first deleted from the DOM, the unmounted stage occurs first, making the alert() visible and preventing the browser from visually removing the component before it is rendered on the screen.
The 'errorCaptured' Hook
The mistakeIf a child or descendant component has an errorCaptured lifecycle hook is triggered.
This hook can be used to log errors, handle errors, or show errors to the user.
Example
CompOne.vue:
Component
This is the component
App.vue:
The 'errorCaptured' Lifecycle Hook
Whenever there is an error in a child component, the errorCaptured() function is called on the parent.
When the button inside the component is clicked, a method will run that tries to do changes to a $refs object that does not exist. This creates an error in the component that triggers the 'errorCaptured' lifecycle hook in the parent, and an alert box is displayed with information about the error.
After clicking "Ok" in the alert box you can see the error in the browser console.
Information regarding the mistake can also be collected as parameters to the errorCaptured() function and these arguments are:
- the error
- the component that triggered the error
- the error source type
In the example below these arguments are captured in the errorCaptured() function and sent to the console:
Example
CompOne.vue:
Component
This is the component
App.vue:
The 'errorCaptured' Lifecycle Hook
Whenever there is an error in a child component, the errorCaptured() function is called on the parent.
Open the browser console to see the captured error details.
The 'renderTracked' and 'renderTriggered' Lifecycle Hooks
When a render function is configured to track, or monitor, a reactive component, the renderTracked hook is triggered. Normally, the renderTracked hook is triggered upon initialization of a reactive component.
When a tracked reactive component changes, the renderTriggered hook is triggered, which causes a fresh render to update the screen with the most recent modifications.
A variable component is known as a reactive component.
A render function is a Vue-compiled function that manages reactive elements. The render function is called when a reactive component changes, and it rerenders the application on the screen.
Only in development mode, the renderTracked and renderTriggered hooks are intended for debugging purposes.
You must copy the code in the example below to your computer and run the program in development mode in order to see the alert() and console.log() from the renderTracked and renderTriggered hooks.
Example
CompOne.vue:
Component One
This is a component.
{{ counter }}
App.vue:
The 'renderTracked' and 'renderTriggered' Lifecycle Hooks
The 'renderTracked' and 'renderTriggered' lifecycle hooks are used for debugging.
This example only works in development mode, so to see the hooks run, you must copy this code and run it on you own computer in development mode.
Note: Because the renderTracked and renderTriggered hooks only function in development mode, the code in the aforementioned example is meant to be copied and run locally on your computer.
The 'activated' and 'deactivated' Lifecycle Hooks
The mounted and unmounted lifecycle hooks for when a component is added or removed from the DOM are visible as we can see above on this page.
The lifecycle hooks marked as activated and deactivated are used to add and remove cached dynamic components—not DOM elements. The dynamic component in the example below is cached using the <KeepAlive> tag.
Example
CompOne.vue:
Component
Below is a log with every time the 'mounted' or 'activated' hooks run.
You can also see when these hooks run in the console.
App.vue:
The 'activated' Lifecycle Hook
In this example for the 'activated' hook we check if the component is cached properly with .
If the component is cached properly with we expect the 'mounted' hook to run once the first time the component is included (must be added to the DOM the first time), and we expect the 'activated' hook to run every time the component is included (also the first time).
To see how the activated and deactivated hooks function, let’s enlarge the previous example. In order to see that the mounted hook runs only when the cached component is added initially and that the unmounted hook never runs for the cached component, let’s also use the mounted and unmounted hooks.
Example
CompOne.vue:
Component
Below is a log with every time the 'activated', 'deactivated', 'mounted' or 'unmounted' hooks run.
You can also see when these hooks run in the console.
App.vue:
The 'activated' and 'deactivated' Lifecycle Hooks
In this example for the 'activated' and 'deactivated' hooks we also see when and if the 'mounted' and 'unmounted' hooks are run.
The 'serverPrefetch' Lifecycle Hook
Only when server-side rendering (SSR) is occurring does the’serverPrefetch’ hook get called.
It would take a lengthy setup and introduction to explain and create an example for the’serverPrefetch’ hook, which is outside the purview of this article.