Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
rodrigocfd Avatar asked Nov 27 '25 10:11

rodrigocfd


2 Answers

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

like image 160
Thomas Champion Avatar answered Nov 30 '25 00:11

Thomas Champion


You can use reactHooks to work with the lifecycle of your application.

In your functional component:

import React, { useEffect } from 'React'

useEffect(() => {
   // your method
}, []);

This will render in the first render.

You can set dependencies to be listened to when its changes.

import React, { useEffect } from 'React'

useEffect(() => {
   // your method
}, [yourDependence]); //it will run every yourDependence change and the first time.
like image 34
Samuel Levy Avatar answered Nov 30 '25 00:11

Samuel Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!