SoFunction
Updated on 2025-04-05

The difference between watch and watchEffect in vue3

The difference between watch and watchEffect in vue3

watch ref

const x = ref(0)
const y = ref(0)

// Single refwatch(x, (newX) => {
  (`x is ${newX}`)
})

// getter functionwatch(
  () =>  + ,
  (sum) => {
    (`sum of x + y is: ${sum}`)
  }
)

// Array of multiple sourceswatch([x, () => ], ([newX, newY]) => {
  (`x is ${newX} and y is ${newY}`)
})

watch reactive

// Provide a getter functionwatch(
  () => ,
  (count) => {
    (`count is: ${count}`)
  },
  // Execute immediately  { immediate: true }
)

Note, do not use the following method:

const obj = reactive({ count: 0 })

// Error, because the parameter obtained by watch() is a numberwatch(, (count) => {
  (`count is: ${count}`)
})

watchEffect

No explicit definition of the parameters to watch

const todoId = ref(0)
watchEffect(async () => {
  const response = await fetch(
    `/todos/${}`
  )
   = await ()
})

The value of todoId is triggered only if it changes

contrast

Both watch and watchEffect can responsively execute callbacks with side effects. The main difference between them is the way to track responsive dependencies:

watch only tracks explicitly listened data sources. It won't track anything accessed in the callback. Also, the callback is triggered only if the data source does change. Watch avoids tracking dependencies when side effects occur, so we can control the triggering timing of the callback function with more precise accuracy.

watchEffect will track dependencies during side effects. It automatically tracks all accessible responsive properties during synchronous execution. This is more convenient, and the code tends to be more concise, but sometimes its responsive dependencies are less explicit.

The general side effect is that this function does something that does not belong to it, such as, or it modifies other external variables, etc.
The function component in react must be a pure function, that is, a function without side effects, because this function will be called many times. If there are side effects such as modifying a global variable, then the accuracy of the variable will not be controlled. (The life cycle function in the react hooks function component is a side effect)
In vue, it is generally said that some behaviors that need to be executed when the state changes, such as when the msg variable changes, I need to reprint it every time the msg variable changes, so this printing behavior can be said to be a side effect (effect)

Extension: What is the difference between watchEffect and watch in vue3 and how to use it

watchEffect and watch in the new Composition API added by vue3
All can be used in the setup() function

watchEffect:
1. It is executed immediately and will be executed once when the page is loaded to collect dependencies.
2. There is no need to pass content that needs to be listened to. It can automatically perceive code dependencies and only needs to pass a callback function.
3. It cannot get the value of the previous data
4. Its return value is used to stop this listening

example:

setup() {
  const { reactive, watchEffect } = vue;
  const data = reactive({ name:'lei' })

  const stop = watchEffect( () => {  // Return value stop is used to stop listening    (  )  // After the page is loaded once, when the log is executed, the log will be executed again when it changes.
    setTimeout( () => {
      stop();  //Stop this monitoring after 5 seconds    }, 5000 )
  })
}

watch: (watch can also be used in setup)
1. Have a certain degree of lazy lazy (but can be configured immediately to make it proactive)
2. The parameters can get the value before the change and the value after the change
3. It can listen for changes in multiple data and bear it with one listener.

example:

const { reactive, watch, ref } = vue;
const name = ref('yang')
// The ref packaged can be directly passed into the first parameter of the watchwatch( name, (newValue,oldValue) => { // The first parameter The data to be monitored  (newValue)  // New value  (newValue)  // Old value},{ immediate: true }) // The third parameter can accept configuration items
const data = reactive({ name:'lei', age:18 })
// However, the values ​​wrapped by reactive cannot be passed directly in. You can use the arrow function to return the data to be listened to.watch( () => , (newValue,oldValue) => { // The first parameter The data to be monitored  (newValue)  // New value  (newValue)  // Old value},{ immediate: true }) //  The third parameter can accept configuration items

The above talks about how to listen for changes in multiple data, and use a listener to carry it. Let's see

example:

const data = reactive({ name:'lei', age:18 })
//Available arrays to receive parameterswatch( [() => , () => ], ([newName, newAge], [oldName, oldAge]) => { 
  (newName, newAge)  // New value  (oldName, oldAge)  // Old value}) 

Whether you need to use watch or watchEffect depends on the business needs

This is the end of this article about the difference between watch and watchEffect in vue3. For more information about the difference between watch and watchEffect, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!