Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Vue js
3.
Composition API
4.
Options API
5.
Composition API vs Options API
6.
Lifecycle of a Vue Component
7.
Lifecycle Hooks in the Composition API
8.
Creation Hooks
8.1.
setup()
8.1.1.
Example
8.1.2.
Output
8.1.3.
Explanation
9.
Mounting Hooks
9.1.
onBeforeMount()
9.1.1.
Example
9.1.2.
Output
9.1.3.
Explanation
9.2.
onMounted()
9.2.1.
Example
9.2.2.
Output 
9.2.3.
Explanation
10.
Updating Hooks
10.1.
onBeforeUpdate()
10.1.1.
Example
10.1.2.
Output
10.1.3.
Explanation
10.2.
onUpdated()
10.2.1.
Example
10.2.2.
Output
10.2.3.
Explanation
11.
Destruction Hooks
11.1.
onBeforeUnmount()
11.1.1.
Example
11.1.2.
Output
11.1.3.
Explanation
11.2.
onUnmounted()
11.2.1.
Example
11.2.2.
Output
11.2.3.
Explanation
12.
Activation Hooks
12.1.
onActivated()
12.1.1.
Example 
12.1.2.
Output
12.1.3.
Explanation
12.2.
onDecativated()
12.2.1.
Example 
12.2.2.
Output
12.2.3.
Explanation
13.
Differences from Options API Lifecycle Hooks
14.
Frequently Asked Questions
14.1.
What is a Vue component?
14.2.
What are life cycle hooks in Vue?
14.3.
How do I mount in VUE JS?
14.4.
What is the difference between created and mounted Vuejs?
14.5.
Is Vue created async?
15.
Conclusion
Last Updated: Mar 27, 2024

Composition API- Lifecycle hooks

gp-icon
Basics of Javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

Hey Ninja! As developers, we strive to create web applications that are functional, efficient, and easy to maintain. Over the years, various approaches and technologies have emerged to help us achieve these goals. One such approach is the Composition API in Vue.js. It provides a new way of structuring our code and managing the lifecycle of our components.

composition API - lifecycle hooks

This article will take a closer look at the Composition API and its lifecycle hooks. We will explore how these hooks can help us manage the state and behaviour of our components and how they differ from the traditional Options API. 

Before starting our discussion, let us talk about the Vue js.

Vue js

vue

Vue.js is an open-source progressive JavaScript framework for building user interfaces and single-page applications. It was created by Evan You in 2014 and has gained a large and active community of developers. It is flexible, intuitive, and efficient. It provides a template-based syntax for defining the structure and behaviour of components. Vue.js also offers a powerful reactivity system, tools for managing states and events, and a rich ecosystem of plugins and libraries. It's famous for building web applications of all sizes and complexity levels.

Now let's see what a composition API is.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Composition API

The composition API is a new feature introduced in Vue.js 3. It helps developers organize and reuse their code when building web applications. Developers can define component logic as reusable functions, which makes their code more modular and easier to understand. The Composition API allows developers to write more flexible and efficient code, valid for larger and more complex applications.

It's a powerful tool for building complex applications and is recommended for use in all Vue projects. 

Options API

In Vue.js, the Options API is one of two ways to define the structure of a component. It is an older approach that has existed since the early versions of Vue.js and is still widely used today.

With the Options API, a component is defined using an object that contains various properties and methods. These properties and methods define the component's data, computed properties, methods, lifecycle hooks, and other features.

The Options API provides a simple and intuitive way to define the structure of a component. However, it can become hard to manage when a component becomes more complex. That's why Vue.js also offers the Composition API, a newer approach that allows developers to organize a component's code into smaller, more manageable pieces.

Do you want to know how the new composition API differs from the options API? Let's find out.

Composition API vs Options API

The main differences between the Options API and the Composition API are as follows.

Options API:

  • Used in Vue 2.x
     
  • Splits options into different properties such as data, computed, methods, and lifecycle hooks.
     
  • Code can become hard to maintain and read as the size of the component grows.
     
  • Limited reusability since some properties are tightly coupled with others.

Composition API:

  • Used in Vue 3.x
     
  • Allows logic to be grouped by feature rather than by property type.
     
  • Code is easier to maintain and read as related logic is grouped.
     
  • Better reusability since the logic can be easily extracted into custom hooks and shared across components.
     

Now, before we dive into the details of lifecycle hooks, let's take a quick look at the lifecycle of a Vue component.

Lifecycle of a Vue Component

Vue components have a well-defined lifecycle comprising various stages. The following diagram shows the different stages of a Vue component's lifecycle:

lifecycle of a Vue component

Each stage of the lifecycle has a specific set of hooks. The Composition API provides access to these hooks and makes it easy to write reusable code that can be used across multiple components.

Now that we have an overview of the Vue component lifecycle, let's dive into the different lifecycle hooks provided by the Composition API.

But what are lifecycle hooks?

Lifecycle Hooks in the Composition API

Lifecycle hooks allow developers to perform actions or logic at critical moments in a component's lifecycle, such as when it's created, mounted, updated, or destroyed. Lifecycle hooks are available and supported by all frameworks like Angular, React, Vue, etc. 

Using these hooks, developers can perform tasks like initializing data, fetching data from APIs, updating the DOM (Document Object Model), or cleaning up resources. Lifecycle hooks are an essential feature of Vue.js. They can help developers build more robust and efficient components. 

The composition API in Vue offers several lifecycle hooks for you to work with. Let us discuss each of them one by one.

In the following examples, we will use the following files.

index.html:

<link rel="stylesheet" href="style.css" />

<div id="app"></div>

<script src="script.js"></script>


package.json:

{
    "dependencies": {
        "vue": "3.2.33"
    }
}


style.css:

body {
    color: #fcbe24;
    padding: 0 24px;
    margin: 0;
}


script.js:

import { createApp } from 'vue'
import App from './App.vue'
console.log('Hello world')
createApp(App).mount('#app')

The following examples will show the code for the App.vue file. The code in all the other files will remain the same.

Creation Hooks

These are the first hooks that run on a webpage. They allow you to perform any action before adding the component to the DOM. They can be used to create and set up components for both server and client-side rendering. 

setup()

The setup hook is the first lifecycle hook in the Composition API. It is used to set up the component's reactive data, register components, and provide any data to be used in the component. 

It is similar to the created hook in the Options API but is more flexible and powerful.

Example

<template>
    <div>
        <h1>{{ message }}</h1>
    </div>
</template>

<script>
import { reactive } from 'vue';

export default {
    setup() {
    
        /*
            Define a reactive state
            object using the `reactive`
            function.
        */
        const state = reactive({
            message: 'Hello, world!'
        });

        /*
            Return an object containing
            the state variable to make
            it available in the template
        */
        return {
            message: state.message
        };
    }
};
</script>

Output

output

Explanation

In this example, we are creating a simple Vue component that displays a message on the page. The setup() function defines reactive properties using the reactive() function, which creates an object that can be used in the template. In the setup() function, we then return the data we want to use in the template using the return statement. In this case, we are returning a single property called message, which is set to a default value of "Hello, world!"

Mounting Hooks

These are the most used hooks by developers. These hooks allow you to access or modify your component before and after the initial render, but they do not run during server-side rendering.

onBeforeMount()

This hook is called right before the component is mounted. It helps perform actions that need to be executed before the component is displayed, such as fetching data from an API.

Example

<template>
    <div>
        <h1>{{ message }}</h1>
    </div>
</template>

<script>
import { reactive, onBeforeMount } from 'vue';

export default {
    setup() {
    
        /*
          Define a reactive state
          object using the `reactive`
          function
        */
        const state = reactive({
            message: 'Hello, world!'
        });

        /*
          Use the `onBeforeMount` hook
          to act before
          the component is mounted
        */
        onBeforeMount(() => {
            console.log('Component is about to be mounted');
        });

        /*
          Return an object containing
          the state variable to make
          it available in the template
        */
        return {
            message: state.message
        };
    }
};
</script>

Output

output

Explanation

In this example, we use the onBeforeMount hook for logging a message to the console just before the component is mounted. This hook takes a callback function as its argument, which will be executed just before the component is mounted. The onBeforeMount hook is called only once, just before the component is mounted.

onMounted()

This hook is called right after the component is mounted. It helps perform actions requiring DOM access, such as initializing third-party libraries or setting up event listeners.

Example

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
import { reactive, onMounted } from 'vue';

export default {
  setup() {
    // Define a reactive state object
    const state = reactive({
      message: 'Hello, world!'
    });

    // Define the onMounted lifecycle hook
    onMounted(() => {
      console.log('Component is mounted!');
    });

    // Return the state variable
    return {
      message: state.message
    };
  }
};
</script>

Output 

output

Explanation

In this example, the onMounted() lifecycle hook logs a message to the console when the component is mounted. 

Updating Hooks

The updating hooks are called whenever a reactive property used by the component changes or re-renders. These hooks allow you to hook into the watch-compute-render cycle for the component.

onBeforeUpdate()

This hook is called right before the component is updated due to a change in its props (properties) or state. It is useful for performing actions that need to be executed before the component is re-rendered, such as resetting some data or cleaning up resources.

Example

<template>
    <div>
        <h1>Current Value: {{ value }}</h1>
        <button @click="updateValue">Update Value</button>
    </div>
</template>

<script>
import { ref, onBeforeUpdate } from 'vue';

export default {
    setup() {
    
        /*
            Define a reactive variable
            with an initial value of 0
        */
        const value = ref(0);

        /*
            Define a function that
            increments the "value" variable
            by 1 when clicked
        */
        const updateValue = () => {
            value.value++;
        };

        /*
            Define the onBeforeUpdate lifecycle
            hook for logging a message when the
            component is about to update
        */
        onBeforeUpdate(() => {
            console.log('Component is about to update! Current value before update:', value.value);
        });

        /*
            Return the reactive variables
        */
        return {
            value,
            updateValue,
        };
    },
};
</script>

Output

output

Explanation

This code defines a reactive variable named "value" with an initial value of 0 and a function named "updateValue" that increments the value by 1 when the button clicks. It also defines an "onBeforeUpdate" lifecycle hook for logging a message when the component is about to update.

onUpdated()

This hook is called right after the component is updated due to a change in its props or state. It helps perform actions requiring DOM access, such as updating third-party libraries or setting up event listeners.

Example

<template>
    <div>
        <h1>Current Value: {{ value }}</h1>
        <button @click="updateValue">Update Value</button>
    </div>
</template>

<script>
import { ref, onUpdated } from 'vue';

export default {
    setup() {
    
        /*
            Define a reactive variable
            with an initial value of 0
        */
        const value = ref(0);

        /*
            Define a function that
            increments the "value" variable
            by 1 when clicked
        */
        const updateValue = () => {
            value.value++;
        };

        /*
            Define the onUpdated lifecycle
            hook for logging a message when
            the component has been updated
        */
        onUpdated(() => {
            console.log('Component has updated! Current value after update:', value.value);
        });

        /*
            Return the reactive variables
        */
        return {
            value,
            updateValue,
        };
    },
};
</script>

Output

output

Explanation

This code defines a reactive variable named "value" with an initial value of 0 and a function "updateValue" that increments the value by 1 when the button clicks. It also uses Vue's "onUpdated" lifecycle hook for logging a message when the component updates.

Destruction Hooks

The destruction hooks allow you to perform actions when the component is destroyed, such as cleanup or sending analytics. They are called when your component is torn down and removed from the DOM. All the destruction hooks are called on the client side.

onBeforeUnmount()

This hook is called right before the component is updated due to a change in its props (properties) or state. It helps perform actions that need to be executed before the component is re-rendered, such as resetting some data or cleaning up resources.

Example

<template>
    <div>
        <h2>{{ message }}</h2>
        <button @click="setMessage">Change Message</button>
    </div>
</template>

<script>
import { ref, onBeforeUnmount } from 'vue';

export default {
    setup() {
    
        /*
            define a reactive variable
            with an initial value of
            "Hello, World!"
        */
        const message = ref('Hello, World!');

        /*
            define a function that changes
            the value of "message" to "Goodbye,
            World!"
        */
        const setMessage = () => {
            message.value = 'Goodbye, World!';
        }
       
        /*
            make a hook that will be
            called just before the
            component is unmounted
        */
        onBeforeUnmount(() => {
            console.log('Component is about to be unmounted!');
        });

        /*
            return the reactive variable
            and the function
        */
        return {
            message,
            setMessage,
        }
    },
};
</script>

Output

Before clicking on the button:

output

After clicking on the button:

output

Explanation

When the component is mounted, the initial value of the message is "Hello, World!" It is displayed along with a button to change the message. Clicking the button changes the message to "Goodbye, World!" When the component is about to be unmounted, the message "Component is about to be unmounted!" is logged into the console.

onUnmounted()

This hook is called right after the component is destroyed. It helps perform actions that require access to the DOM, such as cleaning up third-party libraries or removing event listeners.

Example

<template>
    <div>
        <h2>{{ message }}</h2>
        <button @click="setMessage">Change Message</button>
    </div>
</template>

<script>
import { ref, onUnmounted } from 'vue';

export default {
    setup() {
    
        /*
            define a reactive variable
            with an initial value of
            "Hello, World!"
        */
        const message = ref('Hello, World!');

        /*
            define a function that changes
            the value of "message" to
            "Goodbye, World!"
        */
        const setMessage = () => {
            message.value = 'Goodbye, World!';
        };

        /*
            define a hook that will be
            called when the component
            is unmounted
        */
        onUnmounted(() => {
            console.log('Component has been unmounted!');
        });

        // return the reactive variable and the function
        return {
            message,
            setMessage
        };
    }
};
</script>

Output

output

Explanation

This code is just a modification of the previous code. In this example, the onUnmounted() hook defines a function to be called when the component is unmounted. In this example, the function simply logs a message to the console.

Activation Hooks

Vue 3 Composition API has two additional activation hooks: onActivated() and onDeactivated().

onActivated()

The onActivated() hook is called when a component is activated, which happens when the user navigates to a component. This hook is useful for fetching data or initializing states specific to the activated route.

Example 

App.Vue:

<template>
    <div>
        <!--
            Buttons to switch between
            the A and B tabs
        -->
        <button @click="selectedTab = 'A'">Click to go on A</button>
        <button @click="selectedTab = 'B'">Click to go on B</button>

        <!--
            Render the selected tab
            using dynamic components
        -->
        <keep-alive>
            <component :is="selectedTab" class="tab-area" />
        </keep-alive>
    </div>
</template>

<script>
    import A from './A.vue'
    import B from './B.vue'
    import { ref } from 'vue'

    export default {
        components: {
            A,
            B,
        },
       
         setup() {
        
            /*
               Create a reactive variable
               to track the currently selected tab
            */
            const selectedTab = ref('A')

            /*
               Return the reactive variable
               to be used in the template
            */
            return {
                selectedTab,
            }
        },
    }
</script>


A.vue:

<template>
    <div>
        <h2>A</h2>
        Hello world from A!
    </div>
</template>

<script>
    import { onActivated } from 'vue'

    export default {
        setup() {
        
            /*
               Register a hook that runs
               when the component is activated
            */
            onActivated(() => {
                console.log('A Activated')
            })
        },
    }
</script>


B.vue:

<template>
    <div>
        <h2>B</h2>
        Hello world from B!
    </div>
</template>

<script>
    import { onActivated } from 'vue'

    export default {
        setup() {
        
            /*
               Register a hook that runs
               when the component is activated
            */
            onActivated(() => {
                console.log('B Activated')
            })
        },
    }
</script>

Output

Before clicking on any button.

output

After clicking on the second button.

output

Explanation

Here, the onActivated lifecycle hook is called when a component is activated due to being cached by the keep-alive component. When the user clicks on a button and activates a new component, the onActivated hook is triggered. This hook logs a message to the console indicating which component was just activated.

keep-alive is a component in Vue that caches and preserves the state of components toggled on and off. It allows them to be re-inserted into the DOM without being re-rendered. It improves performance and reduces unnecessary work.

onDecativated()

The onDeactivated() hook is called when a component is deactivated. It happens when the user navigates away from a component. This hook helps clean up any resources specific to the deactivated route.

Example 

App.Vue:

<template>
    <div>
        <!--
            Buttons to switch between
            the A and B tabs
        -->
        <button @click="selectedTab = 'A'">Click to deactivate B</button>
        <button @click="selectedTab = 'B'">Click to deactivate A</button>

        <!--
            Render the selected tab
            using dynamic components
        -->
        <keep-alive>
            <component :is="selectedTab" class="tab-area" />
        </keep-alive>
    </div>
</template>

<script>
    import A from './A.vue'
    import B from './B.vue'
    import { ref } from 'vue'

    export default {
        components: {
            A,
            B,
        },
        setup() {
        
            /*
               Create a reactive variable
               to track the currently selected tab
            */
            const selectedTab = ref('A')

            /*
               Return the reactive variable
               to be used in the template
            */
            return {
                selectedTab,
            }
        },
    }
</script>


A.vue:

<template>
    <div>
        <h2>A</h2>
        Hello world from A!
    </div>
</template>

<script>
    import { onDeactivated } from 'vue'

    export default {
        setup() {
        
            /*
               Register a hook that runs
               when the component is deactivated
            */
            onDeactivated(() => {
                console.log('A Deactivated')
            })
        },
    }
</script>


B.vue:

<template>
    <div>
        <h2>B</h2>
        Hello world from B!
    </div>
</template>

<script>
    import { onDeactivated } from 'vue'

    export default {
        setup() {
        
            /*
               Register a hook that runs
               when the component is deactivated
            */
            onDeactivated(() => {
                console.log('B Deactivated')
            })
        },
    }
</script>

Output

Before clicking on any button:

output

After clicking on the second button:

output

Explanation

In this code, the onDeactivated lifecycle hook is called when a component is deactivated. When the user clicks on a button and deactivates a component, the onDeactivated hook is triggered. This hook logs a message to the console indicating which component was deactivated.

Differences from Options API Lifecycle Hooks

The Composition API allows developers to organize their code more modularly than the Options API. With the Options API, lifecycle hooks are defined in a single object, which can become challenging to manage for complex components. On the other hand, developers can define lifecycle hooks as individual functions with the Composition API. It allows for a better organization by purpose or feature.

Another difference is that the Composition API lifecycle hooks are executed in the order they are defined. In contrast, in the Options API, the order is predefined by Vue. It gives developers more control over the order of execution of lifecycle hooks in the composition API.

It is now time to address some of the frequently asked questions.

Frequently Asked Questions

What is a Vue component?

A Vue component is a self-contained unit of code that defines a specific part of a user interface. Components are reusable and composable and can have their data, methods, and lifecycle hooks.

What are life cycle hooks in Vue?

Lifecycle hooks allow us to know how the library you are using works behind the webpage. They let you know when your component is created, added to the DOM, updated, or destroyed.

How do I mount in VUE JS?

The mounting can be done in Vue js using the onMounted() hook. These hooks run after the instance can be mounted, and the DOM element is replaced. It sends an HTTP request to fetch data that the component will render.

What is the difference between created and mounted Vuejs?

The created hook is called after the instance is created. The mounted hook is called after the instance has been mounted and the DOM element is replaced.

Is Vue created async?

The "created" hook is called when the template is created first but before it is mounted. It is called synchronously, but we can declare the created() method async and perform our asynchronous actions inside.

Conclusion

In this article, we introduced you to the lifecycle hooks of the composition API available in Vue.js. We learned about the difference between the options API and the composition API. We also explored various use cases for creating, mounting, updating, and destroying hooks with the help of examples. 

To learn more about Vuejs, you can refer to these articles.

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninjas!

Previous article
Composition API Setup
Next article
Composition API | Provide/Inject
Guided path
Free
gridgp-icon
Basics of Javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass