Search code examples
javascriptreactjsvue.jsdom

Is there a React equivalent of Vue's nextTick() function?


Vue has this nextTick function, which is an async function that waits until the DOM is flushed. This is particularly useful when you want to perform some operation directly upon an element, like scrolling a DIV with scroll(). This avoids the need to wrap this call into a blind setTimeout().

In React I resorted to setTimeout() in the past. Is there an equivalent to nextTick(), or any better way to do it?


Solution

  • In this case it's possible to use setTimeout to achieve this goal.

    See: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#late_timeouts

    Because it will execute function given in parameter in the end of the current thread, it's close to the behaviour of Vue.nextTick.

    Example : https://codesandbox.io/s/gallant-roman-y0b9un?file=/src/App.js