Vue.js course Β· Module 4: Computed & Watch

watchEffect - Automatic Tracking

5 min read Β·
In this lesson4

The engineer on duty added a third value, the battery level, to a watcher's message but forgot to add it to the array of sources. For a whole week the log showed outdated battery states, because the watcher woke up only when the first two parameters changed. With watch, the list of sources and the body of the callback live separately, so they easily drift out of sync. watchEffect removes that problem: you write only the effect, and Vue works out by itself which data it uses.

Basics of watchEffect

watchEffect takes a single function, called the effect. Vue runs it right away, at the moment the watcher is created, and during that run it records every reactive value the effect read. Those values become dependencies, and a change to any of them runs the effect again.

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

const count = ref(0)
const message = ref('Hello')

// Automatically tracks count and message
watchEffect(() => {
  console.log(`Count: ${count.value}, Message: ${message.value}`)
})

// Will be called:
// 1. Immediately on initialization
// 2. When count changes
// 3. When message changes
</script>

The console shows the first entry before you change anything, and further ones after every change of count or message. The dependencies, however, are only the values read during the latest run: if the effect reads something only inside an if branch that did not execute, a change to that value will not wake it up. Be careful with async effects too, because only the reads made before the first await are tracked. A watcher created in <script setup> stops on its own when the component unmounts, and you will learn the details of stopping in the next lesson.

watch vs watchEffect

Both tools can do the same job; they differ in how they work. Compare them on a single counter, observed in two ways at the same time.

import { ref, watch, watchEffect } from 'vue'

const count = ref(0)

// watch - explicit source, access to oldValue
watch(count, (newVal, oldVal) => {
  console.log(`${oldVal} β†’ ${newVal}`)
})

// watchEffect - automatic tracking, no oldValue
watchEffect(() => {
  console.log(`Count: ${count.value}`)
})

watch receives its source explicitly and provides the old value, so after the counter changes it prints 0 β†’ 1. watchEffect prints just Count: 0 right at startup and then Count: 1, because it does not know the old value - it sees only the current state. The differences in a table:

FeaturewatchwatchEffect
SourceExplicitAutomatic
oldValueYesNo
immediateOptionalAlways
LazyYesNo

The "Lazy" row means that watch waits for the first change by default, while watchEffect starts immediately. Which one should you pick? I recommend watch in code that other people will read: the source is visible in the first line, like in a sensor specification. Reach for watchEffect when the effect uses several values, each of them should trigger it, and the old value is not needed.

Cleanup in watchEffect

Effects often start work that takes time: a server request, an interval, a connection. When id changes before the previous request returns, the late response can overwrite the new one. That is why the effect receives the onCleanup function as its first argument. You register a cleanup in it, and Vue calls it before the next run of the effect and when the watcher stops. An AbortController cancels the request: you pass its signal field to fetch, and its abort() method interrupts the request in flight.

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

const id = ref(1)

watchEffect((onCleanup) => {
  const controller = new AbortController()

  fetch(`/api/artwork/${id.value}`, {
    signal: controller.signal
  })
    .then(res => res.json())
    .then(data => console.log(data))

  // Cleanup - called before each re-run
  onCleanup(() => {
    controller.abort()
  })
})
</script>

When id changes from 1 to 2, Vue first calls the cleanup and aborts the request for number 1, and only then runs the effect for number 2. Cleanup skips no run - the effect still reacts to every change. An aborted fetch rejects its promise with an AbortError, so in a real panel add handling for that one error. You will see the complete pattern in the next lesson. Since Vue 3.5 there is also an importable onWatcherCleanup() function, but it has to be called synchronously, before the first await.

watchPostEffect and watchSyncEffect

By default watchEffect works in flush: 'pre' mode, which means it runs the effect before the DOM update. When you need to read the already refreshed DOM, for example to measure the height of a panel after a row was added, use watchPostEffect, which is watchEffect with flush: 'post'. watchSyncEffect is the variant with flush: 'sync', which runs synchronously on every single change.

import { watchEffect, watchPostEffect, watchSyncEffect } from 'vue'

// Default - before DOM update
watchEffect(() => { /* ... */ })

// After DOM update
watchPostEffect(() => {
  // DOM is already updated here
})

// Synchronously - immediately on change
watchSyncEffect(() => {
  // Warning: may affect performance
})

The order from earliest to latest is fixed: sync immediately on the change, pre before the DOM update, post after it. The synchronous variant does not batch changes, so three assignments in a row mean three runs of the effect. Treat it as an exception, not the default choice.

Remember: watchEffect is the telemetry autopilot - it detects by itself which sensors it uses and starts right away, without waiting for the first change.

Code for this lesson: App.vue
<script setup>
import { ref, watchEffect } from 'vue'

// NOVA LAB - Auto-Tracking System with watchEffect()
const solarPanelAngle = ref(45)
const sunIntensity = ref(70)
const batteryCharge = ref(85)
const powerConsumption = ref(1200)

const logs = ref([])

// watchEffect - automatically tracks ALL reactive dependencies
watchEffect(() => {
  // This will re-run whenever ANY dependency changes
  const effectivePower = Math.floor(
    (solarPanelAngle.value / 90) * sunIntensity.value * 30
  )

  const netPower = effectivePower - (powerConsumption.value / 100)

  const timestamp = new Date().toLocaleTimeString()
  logs.value.unshift({
    time: timestamp,
    message: `Power Generation: ${effectivePower}W | Net: ${netPower > 0 ? '+' : ''}${netPower.toFixed(0)}W`,
    color: netPower > 0 ? '#00ff88' : '#ff0044'
  })

  // Auto-adjust battery based on net power
  if (netPower > 0 && batteryCharge.value < 100) {
    batteryCharge.value = Math.min(100, batteryCharge.value + 0.1)
  } else if (netPower < 0 && batteryCharge.value > 0) {
    batteryCharge.value = Math.max(0, batteryCharge.value - 0.1)
  }
})

// Track battery status separately
watchEffect(() => {
  if (batteryCharge.value < 20) {
    const timestamp = new Date().toLocaleTimeString()
    logs.value.unshift({
      time: timestamp,
      message: 'WARNING: Battery critically low!',
      color: '#ff0044'
    })
  }
})

const effectivePower = ref(0)

watchEffect(() => {
  effectivePower.value = Math.floor(
    (solarPanelAngle.value / 90) * sunIntensity.value * 30
  )
})

function optimizePanels() {
  solarPanelAngle.value = 90
}

function nightMode() {
  sunIntensity.value = 5
  solarPanelAngle.value = 0
}

function dayMode() {
  sunIntensity.value = 85
  solarPanelAngle.value = 65
}
</script>

<template>
  <div class="auto-track">
    <div class="header">
      <h1>NOVA LAB Solar Power System</h1>
      <p class="subtitle">watchEffect() - Auto-Dependency Tracking</p>
    </div>

    <div class="visual-panel">
      <div class="solar-panel" :style="{ transform: `rotate(${solarPanelAngle}deg)` }">
        <div class="panel-surface">
          <div class="panel-grid"></div>
          <div class="angle-display">{{ solarPanelAngle }}Β°</div>
        </div>
      </div>
      <div class="sun-indicator" :style="{ opacity: sunIntensity / 100 }">
        ●
        <div class="sun-rays"></div>
      </div>
    </div>

    <div class="controls-grid">
      <div class="control-card">
        <h3>Sun Intensity</h3>
        <input
          v-model.number="sunIntensity"
          type="range"
          min="0"
          max="100"
          class="slider"
        />
        <div class="value-display">{{ sunIntensity }}%</div>
      </div>

      <div class="control-card">
        <h3>Panel Angle</h3>
        <input
          v-model.number="solarPanelAngle"
          type="range"
          min="0"
          max="90"
          class="slider"
        />
        <div class="value-display">{{ solarPanelAngle }}Β°</div>
      </div>

      <div class="control-card">
        <h3>Power Consumption</h3>
        <input
          v-model.number="powerConsumption"
          type="range"
          min="500"
          max="2500"
          step="100"
          class="slider"
        />
        <div class="value-display">{{ powerConsumption }}W</div>
      </div>

      <div class="control-card battery">
        <h3>Battery Charge</h3>
        <div class="battery-indicator">
          <div
            class="battery-fill"
            :style="{
              width: batteryCharge + '%',
              background: batteryCharge > 50 ? '#00ff88' : batteryCharge > 20 ? '#ffaa00' : '#ff0044'
            }"
          ></div>
        </div>
        <div class="value-display">{{ batteryCharge.toFixed(1) }}%</div>
      </div>
    </div>

    <div class="stats-panel">
      <div class="stat">
        <span class="stat-label">Effective Power:</span>
        <span class="stat-value power">{{ effectivePower }}W</span>
      </div>
      <div class="stat">
        <span class="stat-label">Net Power:</span>
        <span
          class="stat-value"
          :style="{ color: effectivePower - powerConsumption / 100 > 0 ? '#00ff88' : '#ff0044' }"
        >
          {{ effectivePower - Math.floor(powerConsumption / 100) > 0 ? '+' : '' }}{{ effectivePower - Math.floor(powerConsumption / 100) }}W
        </span>
      </div>
    </div>

    <div class="action-buttons">
      <button @click="optimizePanels" class="optimize">Optimize Panels</button>
      <button @click="nightMode" class="night">Night Mode</button>
      <button @click="dayMode" class="day">Day Mode</button>
    </div>

    <div class="log-panel">
      <h3>Auto-Tracking Log</h3>
      <div class="log-list">
        <div
          v-for="(log, index) in logs.slice(0, 10)"
          :key="index"
          class="log-item"
          :style="{ color: log.color }"
        >
          <span class="log-time">[{{ log.time }}]</span> {{ log.message }}
        </div>
      </div>
    </div>

    <div class="info-box">
      <strong>watchEffect():</strong> Automatically tracks all reactive dependencies!
      No need to specify what to watch - it figures it out on its own.
    </div>
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Courier New', monospace;
  background: #0a0e27;
  color: #00ff88;
  padding: 20px;
}

.auto-track {
  max-width: 1000px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #1a1f4c 0%, #0a0e27 100%);
  border: 2px solid #00ff88;
  border-radius: 10px;
}

.header h1 {
  font-size: 2rem;
  margin-bottom: 10px;
  text-shadow: 0 0 20px #00ff88;
}

.subtitle {
  color: #00b4d8;
  font-size: 1.1rem;
}

.visual-panel {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 40px;
  margin-bottom: 30px;
  background: rgba(0, 180, 216, 0.05);
  border: 2px solid #00b4d8;
  border-radius: 10px;
  position: relative;
}

.solar-panel {
  width: 150px;
  height: 200px;
  transition: transform 0.5s ease;
  transform-origin: center center;
}

.panel-surface {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #001a33 0%, #003366 100%);
  border: 3px solid #00b4d8;
  border-radius: 10px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.panel-grid {
  position: absolute;
  width: 90%;
  height: 90%;
  background-image:
    repeating-linear-gradient(0deg, transparent, transparent 30px, #00b4d8 30px, #00b4d8 31px),
    repeating-linear-gradient(90deg, transparent, transparent 30px, #00b4d8 30px, #00b4d8 31px);
}

.angle-display {
  position: relative;
  z-index: 1;
  font-size: 1.5rem;
  font-weight: bold;
  color: #00ff88;
  text-shadow: 0 0 10px #00ff88;
}

.sun-indicator {
  font-size: 5rem;
  filter: drop-shadow(0 0 30px #ffaa00);
  transition: opacity 0.3s ease;
  position: relative;
}

.controls-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.control-card {
  background: rgba(0, 180, 216, 0.05);
  border: 2px solid #00b4d8;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
}

.control-card h3 {
  color: #00b4d8;
  margin-bottom: 15px;
  font-size: 1rem;
}

.slider {
  width: 100%;
  margin: 15px 0;
}

.value-display {
  font-size: 1.5rem;
  font-weight: bold;
  color: #00ff88;
}

.battery-indicator {
  width: 100%;
  height: 30px;
  background: rgba(0, 0, 0, 0.5);
  border: 2px solid #00ff88;
  border-radius: 5px;
  overflow: hidden;
  margin: 15px 0;
}

.battery-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.stats-panel {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  margin-bottom: 20px;
  background: rgba(0, 255, 136, 0.05);
  border: 2px solid #00ff88;
  border-radius: 10px;
}

.stat {
  text-align: center;
}

.stat-label {
  display: block;
  color: #00b4d8;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  text-shadow: 0 0 10px currentColor;
}

.stat-value.power {
  color: #00ff88;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 20px;
}

.action-buttons button {
  padding: 15px 30px;
  font-size: 1rem;
  background: linear-gradient(135deg, #00b4d8 0%, #0077aa 100%);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-family: 'Courier New', monospace;
  font-weight: bold;
  transition: all 0.3s ease;
}

.action-buttons button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 180, 216, 0.3);
}

.optimize {
  background: linear-gradient(135deg, #00ff88 0%, #00cc66 100%) !important;
}

.night {
  background: linear-gradient(135deg, #333366 0%, #1a1a33 100%) !important;
}

.day {
  background: linear-gradient(135deg, #ffaa00 0%, #ff8800 100%) !important;
}

.log-panel {
  background: rgba(0, 0, 0, 0.5);
  border: 2px solid #00ff88;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
}

.log-panel h3 {
  color: #00ff88;
  margin-bottom: 15px;
}

.log-list {
  max-height: 200px;
  overflow-y: auto;
}

.log-item {
  padding: 8px;
  margin-bottom: 5px;
  background: rgba(0, 255, 136, 0.05);
  border-radius: 4px;
  font-size: 0.9rem;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.log-time {
  opacity: 0.7;
}

.info-box {
  background: rgba(0, 255, 136, 0.1);
  border: 2px solid #00ff88;
  border-radius: 10px;
  padding: 15px;
  text-align: center;
  color: #00ff88;
  line-height: 1.6;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the key difference between watch and watchEffect?

  2. 2. When does watchEffect execute for the first time?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Arrange the correct watchEffect syntax:

  • Code editor

    Complete the watchEffect that automatically tracks changes in multiple refs and logs them.

  • Vertical ordering

    Arrange the watchEffect lifecycle from creation to cleanup:

  • Code editor

    Complete the watch observing an array of multiple sources [sensorA, sensorB, sensorC].

  1. QuestionDifference between watch and watchEffect
  2. QuestionwatchEffect immediate
  3. Click in orderwatchEffect syntax
  4. Coding taskPractice: watchEffect
  5. Questionwatch vs watchEffect
  6. QuestionoldValue in watchEffect
  7. Put in orderwatchEffect lifecycle
  8. Coding taskPractice: Watch on Multiple Sources

Useful articles