Vue.js Lifecycle Hooks

Vue.js lifecycle hooks are special functions that get called at specific stages of a component's lifecycle. They provide developers with the ability to add custom behavior during the creation, update, and destruction of Vue components. Understanding these hooks is essential for effective Vue.js development as they offer control over the component's behavior and state at different points in its existence.

What are Vue.js Lifecycle Hooks?

Lifecycle hooks in Vue.js are methods that allow developers to hook into specific moments during a component’s lifecycle. These hooks can be used to run custom logic at various stages, such as when a component is created, mounted to the DOM, updated, or destroyed.

The Lifecycle of a Vue Component

A Vue component goes through several stages from creation to destruction. These stages include:

  1. Creation: The component instance is initialized, and reactive data is set up.
  2. Mounting: The component is inserted into the DOM.
  3. Updating: The component’s reactive data changes, triggering a re-render.
  4. Destruction: The component is removed from the DOM and its resources are cleaned up.
The Lifecycle of a Vue Component, Vue.js Lifecycle Hooks

Lifecycle Hooks Overview

Here is a summary of the available lifecycle hooks:

  • Before Creation: beforeCreate, created
  • Mounting: beforeMount, mounted
  • Updating: beforeUpdate, updated
  • Destruction: beforeDestroy, destroyed

Before Creation Hooks

beforeCreate

The beforeCreate hook is called after the instance has been initialized but before data observation and event/watcher setup. This is useful for initializing non-reactive properties.

				
					<div id="app">{{ message }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},beforeCreate(){console.log('beforeCreate')}})</script> 
				
			

Explanation:

  • The beforeCreate hook logs a message to the console before the component’s data and events are set up.
  • The output will include a console log “beforeCreate” and the rendered message “Hello Vue!”.

created

The created hook is called after the instance has been created, data observation and event/watcher setup are done. This is a good place to fetch initial data from APIs.

				
					<div id="app">{{ message }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:''}},created(){console.log('created');this.message='Hello from created hook!'}})</script> 
				
			

Explanation:

  • The created hook logs a message and sets the message data property.
  • The output will include a console log “created” and the rendered message “Hello from created hook!”.

Mounting Hooks

beforeMount

The beforeMount hook is called right before the component is mounted to the DOM. At this point, the render function has been called the first time.

				
					<div id="app">{{ message }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},beforeMount(){console.log('beforeMount')}})</script> 
				
			

Explanation:

  • The beforeMount hook logs a message to the console right before mounting.
  • The output will include a console log “beforeMount” and the rendered message “Hello Vue!”.

mounted

The mounted hook is called after the component is mounted to the DOM. This is a good place to perform DOM-dependent operations, such as manipulating the DOM or integrating with third-party libraries.

				
					<div id="app">{{ message }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},mounted(){console.log('mounted')}})</script> 
				
			

Explanation:

  • The mounted hook logs a message to the console after the component is mounted.
  • The output will include a console log “mounted” and the rendered message “Hello Vue!”.

Updating Hooks

beforeUpdate

The beforeUpdate hook is called when reactive data changes, right before the DOM is re-rendered. This can be useful for debugging or handling changes in a controlled manner.

				
					<div id="app">
  <p>{{ message }}</p>
  <button @click="updateMessage">Update Message</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},methods:{updateMessage(){this.message='Message Updated!'}},beforeUpdate(){console.log('beforeUpdate')}})</script> 
				
			

Explanation:

  • The beforeUpdate hook logs a message to the console before the DOM is updated.
  • When the button is clicked, the message updates and the output includes a console log “beforeUpdate” and the updated message “Message Updated!”.

updated

The updated hook is called after the DOM has been updated. This is useful for performing actions after the component has been re-rendered.

				
					<div id="app">
  <p>{{ message }}</p>
  <button @click="updateMessage">Update Message</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},methods:{updateMessage(){this.message='Message Updated!'}},updated(){console.log('updated')}})</script> 
				
			

Explanation:

  • The updated hook logs a message to the console after the DOM is updated.
  • When the button is clicked, the message updates and the output includes a console log “updated” and the updated message “Message Updated!”.

Destruction Hooks

beforeDestroy

The beforeDestroy hook is called right before a Vue instance is destroyed. This can be used for cleanup tasks such as removing event listeners.

				
					<div id="app">{{ message }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},beforeDestroy(){console.log('beforeDestroy')},methods:{destroyInstance(){this.$destroy()}}})</script> 
				
			

Explanation:

  • The beforeDestroy hook logs a message to the console right before the component is destroyed.
  • Calling destroyInstance will trigger the beforeDestroy hook, logging “beforeDestroy” to the console.

destroyed

The destroyed hook is called after a Vue instance has been destroyed. This is the last hook that gets called and is useful for final cleanup.

				
					<div id="app">{{ message }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},destroyed(){console.log('destroyed')},methods:{destroyInstance(){this.$destroy()}}})</script> 
				
			

Explanation:

  • The destroyed hook logs a message to the console after the component is destroyed.
  • Calling destroyInstance will trigger the destroyed hook, logging “destroyed” to the console.

Lifecycle Hook Use Cases

Data Fetching

Fetching data from an API when a component is created is a common use case.

				
					<div id="app">{{ data }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{data:null}},created(){fetch('https://jsonplaceholder.typicode.com/posts/1').then(response=>response.json()).then(json=>{this.data=json})}})</script> 
				
			

Explanation:

  • The created hook fetches data from an API and assigns it to the data property.
  • The output will display the fetched data once it is available

Event Listeners

Adding and removing event listeners during component mount and destroy.

				
					<div id="app">{{ message }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{message:'Hello Vue!'}},mounted(){window.addEventListener('resize',this.onResize)},beforeDestroy(){window.removeEventListener('resize',this.onResize)},methods:{onResize(){this.message=`Window width: ${window.innerWidth}`}}})</script> 
				
			

Explanation:

  • The mounted hook adds a resize event listener.
  • The beforeDestroy hook removes the event listener.
  • The onResize method updates the message with the current window width.

Cleanup Activities

Performing cleanup tasks such as clearing intervals or timeouts.

				
					<div id="app">{{ counter }}</div> <script type="litespeed/javascript">new Vue({el:'#app',data(){return{counter:0,intervalId:null}},mounted(){this.intervalId=setInterval(()=>{this.counter++},1000)},beforeDestroy(){clearInterval(this.intervalId)}})</script> 
				
			

Explanation:

  • The mounted hook starts an interval that increments a counter every second.
  • The beforeDestroy hook clears the interval to prevent memory leaks.
  • The output will display an incrementing counter.

Best Practices for Using Lifecycle Hooks

  • Keep Hooks Clean: Avoid adding too much logic in lifecycle hooks. Instead, delegate tasks to methods.
  • Use mounted for DOM Access: Only access the DOM or use third-party libraries in the mounted hook.
  • Clean Up Resources: Always clean up resources such as intervals, event listeners, and subscriptions in the beforeDestroy or destroyed hooks.
  • Use Hooks for Initialization: Fetch data or initialize component state in the created or mounted hooks.

Lifecycle hooks in Vue.js provide powerful tools to manage and control the behavior of your components at different stages of their lifecycle. By understanding and effectively utilizing these hooks, you can perform tasks such as data fetching, event handling, and cleanup in a structured and maintainable way. This chapter has covered the complete range of lifecycle hooks, from basic concepts to advanced use cases, providing a comprehensive guide for building robust Vue.js applications.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India