#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 5 of 37medium

What are Watchers in Vue?

Understanding watch and watchEffect.

What You'll Learn

  • watch function
  • watchEffect function
  • When to use each

watch()

Explicitly watch specific sources.

code.jsJavaScript
import { ref, watch } from 'vue'

const count = ref(0)

// Watch single ref
watch(count, (newValue, oldValue) => {
  console.log(`Count changed from ${oldValue} to ${newValue}`)
})

// Watch with options
watch(count, (newValue) => {
  console.log(newValue)
}, { immediate: true, deep: true })

watchEffect()

Auto-tracks dependencies.

code.jsJavaScript
import { ref, watchEffect } from 'vue'

const count = ref(0)
const name = ref('Vue')

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

Comparison

watchwatchEffect
Explicit sourcesAuto-tracks
Access old valueNo old value
Lazy by defaultRuns immediately
More controlLess boilerplate

Cleanup

code.jsJavaScript
watchEffect((onCleanup) => {
  const timer = setInterval(() => {}, 1000)

  onCleanup(() => {
    clearInterval(timer)
  })
})