šŸ‘ˆ 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!āœØ