SoFunction
Updated on 2025-04-05

A brief analysis of the use of watchEffect in Vue3

Preface

Everyone should be familiar with the watch api in vue2. There is a $watch method in the vue instance in vue2. There is a watch option in sfc(sigle file component). It can implement the behavior we want when an attribute is changed. for example:

  • When the ID changes, get new data from the database.
  • Execute an animation when the property is transformed.
  • When the search conditions change, update the query data.

However, in addition to the watch API, vue3 also has a new watchEffect API. Let's take a look at its usage.

We collect a userID dependency, and then when the userID changes, the watchEffect callback will be executed.

// The example is inspired by [document](/api/#watcheffect)
import { watchEffect, ref } from 'vue'
setup () {
    const userID = ref(0)
    watchEffect(() => (userID))
    setTimeout(() => {
       = 1
    }, 1000)

    /*
      * LOG
      * 0 
      * 1
    */

    return {
      userID
    }
 }

What's the difference with watch?

  • First, we can see from the example code that watchEffect does not need to specify the attributes to listen for. It will automatically collect dependencies. As long as we reference responsive attributes in the callback, when these attributes are changed, this callback will be executed, and watch can only listen for the specified attributes and make changes (the number of attributes can be specified at the same time at the beginning of v3).
  • The second point is that watch can get the new and old values ​​(the value before the update), but watchEffect cannot get it.
  • The third point is that if watchEffect exists, it will be executed once when the component is initialized to collect dependencies (same as computed), and then the collected dependencies change, and this callback will be executed again, but watch does not need it because it specifies the dependency from the beginning.

From their differences, they have their pros and cons. And you can make the right choice in the face of business needs.

watchEffect Advanced

Stop listening

watchEffect will return a function to stop this listening, as follows:

const stop = watchEffect(() => {
  /* ... */
})

// later
stop()

The example comes from the official documentation, with a link above.

If watchEffect is registered in the setup or life cycle, it will automatically stop when the component is unmounted.

Invalid side effect

What is side effect? ​​Unpredictable interface request is a side effect. Suppose we use a user ID to query the user's details, and then we listen to the user ID. When the user ID changes, we will initiate a request. This is very simple, and you can do it with watch. However, if our user ID changes many times during the requesting data, we will initiate multiple requests, and the last returned data will overwrite all user details we returned before. This not only leads to waste of resources, but also does not guarantee the order in which the watch callbacks are executed. And using watchEffect we can do it.

onInvalidate()

The callback passed in onInvalidate(fn) will be executed when watchEffect is re-run or watchEffect is stopped.

watchEffect(() => {
      // Asynchronous API call returns an operation object      const apiCall = someAsyncMethod()

      onInvalidate(() => {
        // Cancel the call to the asynchronous API.        ()
      })
})

With the help of onInvalidate we can make more elegant optimizations to the situation described above.

Summarize

This is the article about the purpose of watchEffect in Vue3. For more information about the purpose of watchEffect in Vue3, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!