Home > database >  How to avoid a small delay in scrolling on react useEffect?
How to avoid a small delay in scrolling on react useEffect?

Time:01-16

I have a component that will automatically keep the scroll position when the child of the overflow: scroll parent is grows/shrinks.

The code that keeps the scroll position works fine. However because I use useEffect to readjust the scroll position. I noticed that there are some delay causing the scroll position to seem like a glitch (scrolled really fast down and back to the initial position).

So I thought that this is caused by react will render the component first and then execute the scrollTop in the useEffect.

Is there any way to avoid this delay?

Maybe this question can be simplified to: How can I render a react component with initial scroll position? (without delay or useEffect?)

CodePudding user response:

It sounds like you may need: useLayoutEffect, it fires immediately after the DOM has been updated, but before the browser has had a chance to paint those changes:

useLayoutEffect is a version of useEffect that fires before the browser repaints the screen.

useEffect on the other hand runs after the browser has painted, so if you have some code inside the useEffect which results in DOM changes, you may notice some flicker because of that.

  • Related