DeployU
Interviews / Frontend Engineering / What is the component lifecycle and how do you use it in Vue?

What is the component lifecycle and how do you use it in Vue?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new component that needs to fetch data from an API when it is created.

You are not sure where to put the data fetching logic in the component’s lifecycle.

The Challenge

Explain what the component lifecycle is in Vue and what the different lifecycle hooks are. Which lifecycle hook would you use to fetch data from an API, and why?

Wrong Approach

A junior engineer might not be aware of the component lifecycle. They might try to fetch the data in the `created` hook, which would work, but it would not be the most optimal solution.

Right Approach

A senior engineer would be able to provide a detailed explanation of the component lifecycle and the different lifecycle hooks. They would also be able to explain the trade-offs between each hook and would have a clear recommendation for which one to use for fetching data.

Step 1: Understand the Component Lifecycle

The component lifecycle is a series of stages that a component goes through, from when it is created to when it is destroyed.

Step 2: The Different Lifecycle Hooks

HookDescription
beforeCreateCalled before the instance is created.
createdCalled after the instance is created.
beforeMountCalled before the component is mounted to the DOM.
mountedCalled after the component is mounted to the DOM.
beforeUpdateCalled before the component is updated.
updatedCalled after the component is updated.
beforeDestroyCalled before the component is destroyed.
destroyedCalled after the component is destroyed.

Step 3: Choose the Right Tool for the Job

For our use case, we should use the mounted hook to fetch the data from the API. This is because we want to make sure that the component is mounted to the DOM before we try to fetch the data.

If we were to fetch the data in the created hook, the component would not be mounted to the DOM yet, so we would not be able to access the component’s template or any of its child components.

Step 4: Code Examples

Here’s how we can use the mounted hook to fetch data from an API:

export default {
  data() {
    return {
      myData: null
    };
  },
  mounted() {
    fetch('https://api.example.com/my-data')
      .then(response => response.json())
      .then(data => {
        this.myData = data;
      });
  }
};

Practice Question

You want to perform an action just before a component is destroyed, such as cleaning up a timer. Which lifecycle hook would you use?