Clément Flodrops
Clément Flodrops

Reputation: 1104

What is the difference between updated hook and watchers in VueJS?

I'm discovering VueJS and I don't understand exactly the differences between updated and watchers.

Updated hook

It is a lifecycle hook. According to the official documentation, it is triggered whenever data changes. So whenever a prop or a data is updated (the value, not only the pointer), updated is called.

Watchers

In the documentation, watchers are compared to computed properties. But in which cases would it be best to use updated instead of watchers ?

It seems that in both cases, DOM is not updated when the callback is called (nextTick() is required if we want to manipulate the changes in the DOM). The only difference I see is that watchers are only triggered when one precise property (or data) is updated where updated is always called.

I can't figure out what are the pros of updating whenever a data changes (updating) if we can be more accurate (watchers).

Here are my thoughts.

Thanks :)

Upvotes: 20

Views: 20457

Answers (2)

Nathan Wailes
Nathan Wailes

Reputation: 12242

I think a better analogous lifecycle hook to the watchers may be the beforeUpdate hook. The updated hook is called after the virtual DOM has re-rendered, whereas beforeUpdate is called before the virtual DOM has re-rendered. You can see a visual representation of this on the diagram you linked to.


in which cases would it be best to use updated instead of watchers ? (...) I can't figure out what are the pros of updating whenever a data changes (updated) if we can be more accurate (watch).

The documentation says that you should prefer a watcher or computed property instead of updated if it is possible to achieve your goal that way. My understanding is that the updated hook was included to allow users to watch for any changes to the virtual DOM (see below).


Here's the explanation from the Vue 2.0 release notes on watch vs. updated:

User watchers created via vm.$watch are now fired before the associated component re-renders. This gives the user a chance to further update other state before the component re-render, thus avoiding unnecessary updates. For example, you can watch a component prop and update the component's own data when the prop changes.

To do something with the DOM after component updates, just use the updated lifecycle hook.

Upvotes: 10

Roy J
Roy J

Reputation: 43899

The lifecycle hooks around update respond to changes in the DOM. Watchers respond to changes in the data. DOM changes are generally in response to data changes, but they might not be data owned by the component in question. One example where updated could be used is noticing that slot content has updated.

Upvotes: 28

Related Questions