DeployU
Interviews / Frontend Engineering / What is the difference between `computed` properties and `watchers` in Vue?

What is the difference between `computed` properties and `watchers` in Vue?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at an e-commerce company. You are building a new component that needs to display a user’s full name, which is derived from their first name and last name.

You are not sure whether to use a computed property or a watcher to do this.

The Challenge

Explain the difference between computed properties and watchers in Vue. What are the pros and cons of each approach, and which one would you choose for this use case?

Wrong Approach

A junior engineer might think that they are interchangeable. They might try to use a `watcher` to do something that could be more easily done with a `computed` property.

Right Approach

A senior engineer would be able to provide a detailed explanation of the differences between `computed` properties and `watchers`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.

Step 1: Understand the Key Differences

Featurecomputedwatchers
PurposeTo compute a new value based on existing data.To perform an action in response to a change in the data.
CachingCached, the computed property is only re-evaluated when one of its dependencies changes.Not cached, the watcher is called every time the data changes.
Use CasesWhen you need to derive a new value from existing data.When you need to perform an asynchronous or expensive operation in response to a change in the data.

Step 2: Choose the Right Tool for the Job

For our use case, we should use a computed property. This is because we are deriving a new value (the full name) from existing data (the first name and the last name).

Step 3: Code Examples

Here are some code examples that show the difference between the two approaches:

computed property:

export default {
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    };
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
};

watcher:

export default {
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe',
      fullName: 'John Doe'
    };
  },
  watch: {
    firstName(newValue) {
      this.fullName = `${newValue} ${this.lastName}`;
    },
    lastName(newValue) {
      this.fullName = `${this.firstName} ${newValue}`;
    }
  }
};

As you can see, the computed property is much more concise and elegant than the watcher.

Practice Question

You want to fetch data from an API whenever a user's ID changes. Which of the following would you use?