Component Lifecycle Hooks — Vue

Sandesh Rijal
2 min readApr 28, 2021

--

It is about a different phases a component goes in a Vue application. A Vue component can go through 4 phases.

  1. Creation
  2. Mounting
  3. Updating
  4. Unmounting

Lifecycle hooks are methods that allow us to hook into or tap into these different phases in the lifecycle of a component and execute some code. There are total of 13 lifecycle hooks that we can use in a component. However, not all are crucial in building a Vue applications.

Creation:

This is the first phase. That is your component is about to be created. In this phase we can tap into two methods: beforeCreate() and created(). All your data properties, computed properties, methods and watchers are not processed by the component in the beforeCreate() method but they are processed and ready to use in the created() method. Because of this created is the method you are more likely to be using in your project. The created() method is the best place to make any API call from your component. For example: searching the user detail when the user navigating through the user profile page.

Mounting:

It is during this phase the component template or the HTML is actually mounted onto the DOM which you see in the browser. In this phase we have two methods: beforeMount() and mounted(). This should be used if the DOM of your component needs to be modified immediately before or after the component is initially rendered. The most commonly used method in this phase is the mounted() method since the DOM is ready for access and manipulation. Possible use case is focusing a Input element by directly getting hold of it’s DOM node.

Updating:

This phase is triggered when a reactive property such as data or computed properties used by component changes or the component re-renders. Again, there are two methods: beforeUpdate() and updated(). beforeUpdate() is called when the data changes but before the DOM is patched. It can be used to access the existing DOM before and update and remove event listeners on elements that might be removed after the update. updated() is called after the patch have been applied to DOM. Similar to Mounting you can perform DOM dependent operations in this method as well.

Unmounting:

This relates to the point when your component is about to be removed from the DOM. There are two methods in this phase: beforeUnmount() and unmounted(). The most relevent method is probably beforeUnmount() method as your component is fully functional. You can perform some cleaning up like cancelling network requests, removing manually added event listners, cancelling subscriptions and also invalidating timers from setTimeout or setInterval.

--

--

No responses yet