Vue watch and watchEffect

Vue watch and watchEffect

Watchers let you run side effects (API calls, logging, DOM manipulation) in response to reactive state changes.

watch() — explicit dependency

import { ref, watch } from 'vue'

const query = ref('')

// Watch a single ref
watch(query, (newVal, oldVal) => {
  console.log(`Query changed from "${oldVal}" to "${newVal}"`)
  fetchResults(newVal)
})

// Watch with options
watch(query, fetchResults, {
  immediate: true,  // run immediately on mount
  deep: true,       // deep watch for nested objects
})

// Watch multiple sources
const page    = ref(1)
const perPage = ref(10)

watch([query, page, perPage], ([q, p, pp]) => {
  fetchResults(q, p, pp)
})

watchEffect() — automatic dependency tracking

import { ref, watchEffect } from 'vue'

const userId = ref(1)

// Runs immediately; tracks any reactive values accessed inside
watchEffect(async () => {
  const data = await fetchUser(userId.value)  // tracked automatically
  user.value = data
})

Stopping a Watcher

const stop = watch(query, fetchResults)
// Later:
stop() // unregister the watcher