👈 Return to blog

Track your variables: Watchers 👀

Overview

Watchers are essential features for software development with Vue. In this article, we’ll dive deeper into Vue Watchers and explore how they can be used to improve Vue application development.


Let’s start🤙🏻

What are Watchers? 🤔

Watchers enable you to monitor changes to data properties and execute custom logic when these properties change. This functionality is invaluable when you need to respond to changes in your application’s state. The difference between Computed Properties is that it tracks variable changes and triggers “side effects”. There are two ways to handle Watchers: watch() and watchEffect().


How to works watch()?

Let’s analyze the following example:

<script setup>
  import { ref, watch } from "vue";

  const isActive = ref(false);

  watch(isActive, () => console.log(`The switch is: ${isActive.value}`));
</script>

<template>
  <input type="checkbox" :value="isActive" />
</template>

The example above is the base case of how to use the watch() API: it takes as arguments the source (isActive in this case) and a callback describing the custom logic. It will trigger whenever isActive changes value.


…and watchEffect()?

watchEffect() is similar to watch() API, but with a more streamlined syntax and a few key differences:

The following example resumes the previous one using watchEffect():

<script setup>
  import { ref, watchEffect } from "vue";

  const isActive = ref(false);

  watchEffect(() => console.log(`The switch is: ${isActive.value}`));
</script>

<template>
  <input type="checkbox" :value="isActive" />
</template>

Watchers vs Computed Properties 👊

Watchers and Computed Properties may be similar but not the same, and there are contexts in which you need to choose carefully.


Use Watchers when:

Use Computed Properties when:

Using Watchers is much more expensive than using Computed Properties. It’s recommended to use Computed Properties when there may be several status variations.🧠


Conclusion

Watchers are a powerful feature for handling reactivity. They allow to respond to data changes with custom logic, making your code more organized and maintainable.

Incorporate Watchers into your projects, experiment with different use cases, and discover how they can simplify complex reactivity scenarios.


Happy coding!✨