When to use NextTick API in Vue.js

When to use NextTick API in Vue.js

NextTick is one of the cool feature in the VUE world. In Vue.js, When we change the state, it will not update/affect the DOM instantly or synchronously. Rather It will collect the state changes and do the DOM update once asynchronously no matter how many state changes you have made.

NextTick API

NextTick API in Vue.js

<script>
import { nextTick } from 'vue'

export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    async increment() {
      this.count++

      // DOM not yet updated
      console.log(document.getElementById('counter').textContent) // 0
    }
  }
}
</script>

<template>
  <button id="counter" @click="increment">{{ count }}</button>
</template>

In the above program, we are changing the state of count by doing count++. But this will not update the DOM instantly rather the vue.js frameworks collects this information in the backend. After the whole execution of increment() method, It will update the DOM asynchronously.

But the problem is document.getElementById('counter').textContent) returns 0 in the increment() method. so if someone wants to use DOM element immediately, which is not possible in Vue.js directly. That’s where we have to use nextTick global API. nextTick allows you to execute code after you have changed some data and Vue.js has updated the virtual DOM based on your data change, but before the browser has rendered that change on the page.

We can pass the callback function to the nextTick(callback(){}) which can be triggered after the successful DOM update. You can either pass a callback as an argument, or await the returned Promise.

import { nextTick } from 'vue'

export default {
  methods: {
    increment() {
      this.count++
      nextTick(() => {
        // access updated DOM
      })
    }
  }
}

Why Not SetTimeout ?

Some people would think, why not setTimeOut!. We can also use setTimeOut But the problem is When you invoke setTimeout

setTimeout(function() { 
    // access updated DOM
}, 100);

then the browser would have a chance to update the page, and then your callback would get called. So the UI will render the old record first and then the new record will come. It’s not look good right. But with the help of nextTick() we can change the DOM value before being render into the screen. That’s the beauty of this API in Vue.js

Summary

nextTick() can be used immediately after a state change to wait for the DOM updates to complete. We should not use setTimeOutto update the DOM rather should prefer nextTick()

Leave a Reply

%d bloggers like this: