The Composition API watchEffect Function — Transcript

Transcript of the free Vue.js lesson The Composition API watchEffect Functionwatch the video lesson.

Another function that the Composition API provides that's useful for triggering side effects whenever data changes is a function called watchEffect. There are three primary differences between watchEffect and watch. The first is that watchEffect will always fire immediately upon watching. It's the same thing as passing the immediate option to watch.

The second difference is that we don't have to manually tell it what data to depend on. by passing it as the first argument. Instead, watchEffect knows what reactive data we use inside the callback function and just automatically watches it to change. The last difference is that we don't have access to the old value of the data dependency.

Let's see that in action. I'll import watchEffect and switch it out with watch. Now, we no longer have to manually tell it what to watch. Instead, we can reference the cart directly in the callback function, and Vue will automatically pick it up as a dependency, and run the callback function whenever it changes.

And of course, new value and old value are no longer provided. You see now that as soon as we visit the page in the browser, we get that immediate alert, and adding items to the cart still triggers it, just like with Watch. Also, just like with Watch, we have the ability to stop the watcher. This begs the question, when is a good time to use watch and when is a good time to use watch effect?

I think in our case, it's pretty clear. The alert on the page load just won't work. But what about less obvious scenarios? I think the decision can be made by asking yourself just these two questions.

Do I need access to the old value or Will it be a problem if the callback fires immediately? If the answer to either of those questions is yes, then you should use plain old watch. If you can answer no to both of those, then there's no harm in using watch effect. All right, let's change our code back to watch since our answer to the second question is yes.