Track your variables: Watchers 👀
Tags: vue, javascript, frontend, webdev
Published: 2023-10-10 06:02:00

## 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](https://dev.to/dvalin99/computed-properties-482) 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:

```html
<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.
<br/>

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

- **Declarative Syntax**: `watchEffect()` uses a more declarative syntax compared to the `watch()` API. Instead of specifying what data property or properties you want to watch, you place your code directly inside the `watchEffect()` function, and it automatically detects the dependencies.
<br/>

- **Automatic Dependency Tracking**: `watchEffect()` automatically tracks the reactive dependencies within its function body. This means that you don't need to specify dependencies explicitly as you would with the watch option. Vue figures out the dependencies for you, making the code more concise and less error-prone.
<br/>

- **Immediate Execution**: `watchEffect()` runs its code immediately when you first create it, and then it re-runs whenever any of its tracked dependencies change. This is useful for scenarios where you want to perform an initial setup or computation and then react to subsequent changes.

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

```html
<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](https://dev.to/dvalin99/computed-properties-482) may be similar but not the same, and there are contexts in which you need to choose carefully.

**Use Watchers when**:

- Need to respond to changes in data with custom, imperative logic.
- Need to perform asynchronous operations.
- Need access to both old and new values of a property.
- Want to watch multiple properties independently.
<br/>

**Use Computed Properties when:**:

- Want to compute or derive a new value based on existing data.
- Want to benefit from automatic dependency tracking and performance optimization.

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!✨

---

Hi👋🏻
My name is Domenico, software developer passionate of Vue.js framework, I write article about it for share my knowledge and experience.
Don't forget to visit my Linktree to discover my projects 🫰🏻

Linktree: https://linktr.ee/domenicotenace

Follow me on dev.to for other articles 👇🏻

{% embed https://dev.to/dvalin99 %}