Getting started General
Components
Forms
Trends
Utilities
Plugins Sass Migrate from v1
  Join us
  Vue Articles

Vue nextTick(): What It Does and When to Use It

Vue

Learn what Vue nextTick() does, why the DOM is not updated right after a state change, and how to use await nextTick() and this.$nextTick() with practical Vue 3 examples.

Vue nextTick() waiting for the DOM update after a state change
Vue nextTick(): What It Does and When to Use It

Vue nextTick is a function that waits for Vue to finish updating the DOM after you change some reactive state. When you write count.value++, the screen is not updated on the next line. Vue schedules the update, and nextTick() lets you run code once it is done:

import { ref, nextTick } from 'vue';

const count = ref(0);

async function increment() {
  count.value++;
  // The DOM still shows the old value here

  await nextTick();
  // The DOM is now up to date
}

You only need it when your code reads or touches the DOM right after a change: focusing an input that just appeared, scrolling to a new message, measuring an element. This guide explains why Vue works this way, how to use nextTick() in the Composition API and the Options API, and the mistakes that make it look like it is not working. Every example was checked against Vue 3.5.

Why the DOM Is Not Updated Right Away

Vue does not touch the DOM each time a reactive value changes. It puts the component update in a queue and applies all pending changes together, a bit later in the same tick of the event loop. Take this component:

<script setup>
import { ref, nextTick } from 'vue';

const count = ref(0);
const counter = ref(null);

async function increment() {
  count.value++;
  console.log(counter.value.textContent); // '0'

  await nextTick();
  console.log(counter.value.textContent); // '1'
}
</script>

<template>
  <button @click="increment">
    Count: <span ref="counter">{{ count }}</span>
  </button>
</template>

Right after count.value++, the state is 1 but the <span> still contains 0. After await nextTick(), it contains 1.

This delay is deliberate. If a function changes the same value three times, Vue renders the component once, not three times:

function incrementThreeTimes() {
  count.value++;
  count.value++;
  count.value++;
  // The component re-renders only once, with count = 3
}

Batching updates this way avoids useless work and keeps large pages fast. The cost is that the DOM lags behind your state for a moment, and nextTick() is how you wait for it to catch up.

nextTick() Syntax in Vue 3

In Vue 3, nextTick is imported from 'vue'. It accepts an optional callback and always returns a Promise:

function nextTick(callback?: () => void): Promise<void>

You can use it in two ways. Both wait for the same DOM update:

import { nextTick } from 'vue';

// 1. With await (recommended)
await nextTick();
// DOM updated

// 2. With a callback
nextTick(() => {
  // DOM updated
});

The await form is easier to read, especially when you do several things in a row, and it is what the official Vue documentation for nextTick() uses in its examples.

this.$nextTick() in the Options API

With the Options API, every component instance has a $nextTick() method. It does the same thing as nextTick(), but it also binds this in the callback to the current component:

export default {
  data() {
    return { message: 'Hello' };
  },
  methods: {
    async updateMessage() {
      this.message = 'Updated';

      await this.$nextTick();
      console.log(this.$refs.text.textContent); // 'Updated'
    }
  }
};

this.$nextTick(function () { ... }) works too: inside that regular function, this is the component instance.

How nextTick Works Under the Hood

When a reactive value changes, Vue adds the component's update job to a queue and schedules a flush of that queue as a microtask, using a resolved Promise. nextTick() returns a Promise that resolves after that flush. Two consequences follow:

  • Any synchronous code after a state change still sees the old DOM, because the flush has not run yet.
  • nextTick() resolves before any setTimeout() callback, since microtasks run before the next task of the event loop.

Calling nextTick() when nothing is pending is harmless: it simply resolves on the next microtask.

Practical Examples of nextTick in Vue

1. Focus an Input That Was Just Displayed

This is the most common use case. When an <input> is rendered with v-if, it does not exist yet on the line where you switch the condition, so its template ref is null:

<script setup>
import { ref, nextTick } from 'vue';

const editing = ref(false);
const input = ref(null);

async function startEditing() {
  editing.value = true;
  // input.value is still null here

  await nextTick();
  input.value.focus();
}
</script>

<template>
  <input v-if="editing" ref="input" @blur="editing = false" />
  <button v-else @click="startEditing">Edit</button>
</template>

2. Scroll a Chat to the Last Message

After pushing a message, the list is not taller yet. Wait for the new <li> to be rendered, then scroll:

<script setup>
import { ref, nextTick } from 'vue';

const messages = ref([]);
const list = ref(null);
let nextId = 0;

async function addMessage(text) {
  messages.value.push({ id: nextId++, text });

  await nextTick();
  list.value.scrollTop = list.value.scrollHeight;
}
</script>

<template>
  <ul ref="list" class="chat">
    <li v-for="message in messages" :key="message.id">{{ message.text }}</li>
  </ul>
</template>

Without nextTick(), the scroll would stop one message short every time.

3. Measure an Element After Its Content Changes

Sizes and positions only change once the DOM is updated. Read them after nextTick(), not before:

const text = ref('');
const box = ref(null);
const height = ref(0);

async function setText(value) {
  text.value = value;

  await nextTick();
  height.value = box.value.offsetHeight;
}

4. Initialize a Third-Party Library on a New Element

Libraries such as chart, map or editor widgets need a real DOM element. If that element appears with v-if, create the instance after the next tick:

const showChart = ref(false);
const canvas = ref(null);

async function openChart() {
  showChart.value = true;

  await nextTick();
  new Chart(canvas.value, chartConfig);
}

5. Wait for the DOM in Component Tests

Tests hit the same delay. In Vue Test Utils, methods like trigger() and setValue() already return nextTick(), so you just await them. When you change state directly, await nextTick() yourself:

import { mount } from '@vue/test-utils';
import { nextTick } from 'vue';
import Counter from './Counter.vue';

test('updates the count', async () => {
  const wrapper = mount(Counter);

  // trigger() returns nextTick(), so awaiting it is enough
  await wrapper.find('button').trigger('click');
  expect(wrapper.text()).toContain('1');

  // A direct state change needs an explicit nextTick()
  wrapper.vm.count = 5;
  await nextTick();
  expect(wrapper.text()).toContain('5');
});

nextTick vs setTimeout, watch and onUpdated

Several tools run code "after something changed". They do not run at the same moment:

Tool When it runs Use it for
nextTick() Right after the pending DOM update One-off DOM work following an action in your code
setTimeout(fn, 0) In a later task, after Vue and possibly after a browser paint Nothing DOM-related in Vue: it works by accident and can flicker
watch(source, fn, { flush: 'post' }) After the DOM update, every time the source changes Reacting to a value, whatever changed it
onUpdated() After every re-render of the component, for any reason Rare cases that must follow every render

The watcher option is worth knowing. By default, a watcher runs before the DOM update, so it sees the old DOM. With flush: 'post', it runs after, and you do not need nextTick() inside it:

import { watch } from 'vue';

// Runs before the DOM update: sees the old DOM
watch(count, () => {
  console.log(counter.value.textContent); // '0'
});

// Runs after the DOM update: sees the new DOM
watch(count, () => {
  console.log(counter.value.textContent); // '1'
}, { flush: 'post' });

A simple rule: use nextTick() when the DOM work belongs to a specific action (a click, a submit), and a post-flush watcher when it should happen every time a value changes.

Common Mistakes When nextTick Is "Not Working"

Forgetting to Await It

Calling nextTick() on its own line does nothing. You must either await it or pass a callback:

// Wrong: the next line does not wait
editing.value = true;
nextTick();
input.value.focus(); // TypeError: input.value is null

// Right
editing.value = true;
await nextTick();
input.value.focus();

Registering the Callback Before Changing the State

A callback passed to nextTick() before the state change can run before the update it was supposed to wait for:

// Wrong: the callback is queued before the update
nextTick(() => {
  console.log(counter.value.textContent); // still the old value
});
count.value++;

// Right: change the state first, then wait
count.value++;
await nextTick();
console.log(counter.value.textContent); // new value

Expecting nextTick to Wait for Your Data

nextTick() waits for Vue to render, not for an API call. If the data is still loading, there is nothing new to render yet. Wait for the data first, then for the DOM:

async function loadUsers() {
  users.value = await fetchUsers(); // 1. wait for the data
  await nextTick();                 // 2. wait for the DOM
  list.value.scrollTop = 0;
}

Using It in onMounted() for the Component's Own DOM

When onMounted() runs, the component's template is already in the DOM and its template refs are set. Wrapping that code in nextTick() adds nothing. You only need it there if onMounted() itself changes state and then reads the result in the DOM.

Calling Vue.nextTick() in Vue 3

Vue 3 removed most global APIs so that bundlers can drop what you do not use. Vue.nextTick() no longer exists: import nextTick from 'vue' instead, or use this.$nextTick() in the Options API.

nextTick in Vue 2 vs Vue 3

  • Vue 2: available as the global Vue.nextTick() and as this.$nextTick(). It returns a Promise when called without a callback. Internally it prefers Promises and falls back to older mechanisms in environments without them.
  • Vue 3: imported with import { nextTick } from 'vue', always returns a Promise, and this.$nextTick() is still available in the Options API.

The behavior you rely on is the same in both versions: change the state, await the next tick, then work with the DOM. Vue 2 reached its end of life on December 31, 2023, so new code should target Vue 3.

Frequently Asked Questions

What does nextTick do in Vue?

It waits until Vue has applied pending state changes to the DOM, then resolves its Promise or runs its callback. Use it when your code needs to read or modify the updated DOM right after a change.

Does nextTick return a Promise?

Yes. In Vue 3, nextTick() always returns a Promise, so you can write await nextTick(). The callback is optional.

What is the difference between nextTick() and this.$nextTick()?

They wait for the same update. nextTick() is imported from 'vue' and used in the Composition API. this.$nextTick() is the Options API version, which binds this in the callback to the component instance.

Is nextTick the same as setTimeout(fn, 0)?

No. nextTick() is a microtask tied to Vue's update queue and runs right after the DOM update. setTimeout() waits for a later task, so it runs later and the browser may paint an intermediate state in between.

Why is my template ref still null after a change?

The element is created during the next DOM update, not when you change the state. Put await nextTick() between the state change and the line that uses the ref.

Conclusion

Vue batches DOM updates for performance, which means the DOM is briefly behind your state after every change. Vue nextTick closes that gap: change the state, await nextTick(), then work with the DOM. Use it for focus, scroll and measurement right after an action, prefer a flush: 'post' watcher when the work should follow every change of a value, and leave setTimeout() out of it.

If this in Options API callbacks still feels confusing, our guide to the JavaScript bind() method explains how it is set. For more on Promises and timers, read how to wait and sleep in Node.js.

Start Building with Axentix

Ready to create amazing websites? Get started with Axentix framework today.

Get Started

Related Posts