Watching Out for Watchers in Vue
Elabid Asmaa

Elabid Asmaa @elabid_asmaa

About: Asmaa Elabid , a Developer dedicated to creating scalable, user-focused web applications. Focused on solving problems and delivering seamless user experiences.

Location:
Morocco
Joined:
Jul 15, 2024

Watching Out for Watchers in Vue

Publish Date: Mar 11
1 0

1. What is a Watcher?

A watcher in Vue allows us to react to changes in reactive state.
Example:

watch(userId, (newId) => {
  fetchUser(newId)
})
Enter fullscreen mode Exit fullscreen mode

When userId changes, the watcher runs the function.

2. The Problem With Overusing Watchers

Watchers are powerful but can easily be overused.

Common issues:

⚠️ Hidden logic
It becomes hard to understand what triggers what.

⚠️ Debugging complexity
Many watchers can create chains of reactions.

⚠️ Performance issues
Deep watchers or multiple watchers may trigger frequently.

⚠️ Unnecessary reactivity
Sometimes we watch values when we could compute them instead.

Example of problematic code:

watch(a, () => {
  b.value = a.value * 2
})
Enter fullscreen mode Exit fullscreen mode

This is unnecessary because it should be a computed value.

3. Prefer Computed Over Watch When Possible

If you are deriving state from other state, use computed.

Computed properties are:

  • easier to understand

  • automatically optimized by Vue

4. Simple Rule of Thumb

Use:

🧠 computed → derived state
👀 watch → side effects only

If you find yourself watching something just to update another reactive variable, it's probably the wrong approach.

Comments 0 total

    Add comment