Vue 3 Composition API - watchEffect Vs watch
watchEffect
seems to be a simplified watch
and the main differences are
- Only accepts a function
watch
can accept either a function or one or more reactive properties.
- Runs immediately when defined and when reactive dependencies change
watch
only runs when reactive dependencies change
I would use:
watchEffect
when I want to watch multiple reactive properties and I don't care about old valueswatch
when I want to watch one specific reactive properties and I may want old value
Note, above is what I would use them for, but may not be their only usage.
Also found in docs regarding the difference:
Compared to watchEffect, watch allows us to:Perform the side effect lazily;Be more specific about what state should trigger the watcher to re-run;Access both the previous and current value of the watched state.
watchEffect
is something introduced in Vue3 with its composition api. The reason to have both watchEffect
and watch
, as I understand, is to keep the semantics of watch
as close as possible to that of Vue2. The birth of watchEffect, if you are interested, can be traced back to here and here
As it stands today, watchEffect
is an immediate/eager watch that uses a more concise/consistent syntax (consistent with computed):
watchEffect
does not accept explicit watch sources, but instead automatically figures out all the dependencies by immediately executing the callback (or effect as how it is called in the source code), similar to howcomputed
works. ThereforewatchEffect
must run the effect immediately. And because of this, there is a common trap (at least I have to keep reminding myself of it constantly) when setting upwatchEffect
: you need to make sure that during the first execution of yourwatchEffect
, all of the dependencies are indeed accessed. How would some dependency escape from being accessed? Watch for conditional statements.watchEffect
will run its effect immediately as mentioned above.watchEffect
is a deep watch. This is something I am not sure whether it is intended or not. If you use a reactive object inside your effect, any change on that object will cause the effect to rerun, even if the changed property is not the one you accessed or is nested.
If Vue 3 is designed from scratch or there is no concern of maintaining backward compatibility, I would imagine there will only be watchEffect