WTF is "nextTick()"?

·

3 min read

$nextTick is a somewhat mysterious property of Vue that is used for asynchronous DOM updates. It's a function that offers you some extra control over the standard reactive data flow. In order to understand this, let's define how Vue's reactivity works.

Vue Reactivity

Data is passed into a Vue component as a JavaScript object. Vue adds getter and setter functions to this object. Whenever this data changes, Vue will trigger either the getter function to collect this change as a dependency, or a setter function to notify the component that something has changed.

"Every component instance has a corresponding watcher instance, which records any properties “touched” during the component’s render as dependencies. Later on when a dependency’s setter is triggered, it notifies the watcher, which in turn causes the component to re-render." - vuejs.org/v2/guide/reactivity.html

image.png

You can learn more about this with this free lesson on Vue Mastery.

Where does $nextTick() fit in all this?

Here is the definition of nextTick straight from the proverbial horse's mouth:

Vue.nextTick( [callback, context] ) Arguments: {Function} [callback] {Object} [context] Usage: Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update. -- vuejs.org/v2/api/#Vue-nextTick

Say what? Let's break this down.

Vue.nextTick: This indicates that nextTick is a property on the Vue instance.

( [callback, context] ): The callback is the name of the function to execute on the next tick. The context is the detail inside the function's curly brackets that define what the function should do.

Defer the callback: Wait to perform this function

to be executed after the next DOM update cycle: Until the next DOM update cycle. (The DOM update cycle is the loop displayed in the image above.)

Use it immediately after you've changed some data to wait for the DOM update.: This is the most important part of the concept of nextTick. Its usefulness lies in the fact that it can delay something until the DOM has re-rendered, ensuring that this callback function will run with the latest data.

Vue's reactivity system does a great job of keeping data updated, but nextTick is like a surgical scalpel that allows you to cut into the DOM update cycle and execute very granular control over it. It's not a tool you'll need every day, but it is a good thing to have on the table. If you ever get an error like Uncaught (in promise) DOMException, nextTick might be what you use to resolve it. Essentially, what nextTick says is:

"Wait until this current thing is done before executing this other thing."

Check out the resources below for code examples of how nextTick works.

Resources