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

Time:06-22

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?

CodePudding user response:

In React class components, you can use the componentDidMount for the 1st render & componentDidUpdate for the subsequent renders, to perform DOM updates.

componentDidMount

Initialization that requires DOM nodes should go here.

See https://reactjs.org/docs/react-component.html#componentdidmount

componentDidUpdate

Use this as an opportunity to operate on the DOM when the component has been updated.

See https://reactjs.org/docs/react-component.html#componentdidupdate

For functional components, there is the useEffect hook.

See https://reactjs.org/docs/hooks-effect.html

CodePudding user response:

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.
  • Related