Subscribe on changes!

watchEffect runs even though its dependencies have not changed

avatar
Aug 25th 2021

Version

3.2.6

Reproduction link

SFC Playground

Steps to reproduce

click inc button a few times and watch console logs

What is expected?

I would expect second watchEffect (watchEffect 2) to run only once when value of isLessThanFive actually changes

watchEffect

Runs a function immediately while reactively tracking its dependencies and re-runs it whenever the dependencies are changed.

What is actually happening?

watchEffect is called each time count is incremented

avatar
Aug 25th 2021

That's because of the computed property and a common misunderstanding about how they work.

I'm having a blog post about that topic ready, just don't know yet where to post it.

The gist of it is: computed properties are evaluated when they are read. So the return value is only known when they are read. before that, Vue only knows that a dependency changed.

So Vue has to trigger all reactive dependents that have the computed as a dependency.

We had several rounds of discussions and attempts at getting around that, even back in Vue 2, but all had to be abandoned due to edge cases we couldn't cover, essentially.