'scrollheight is not properly calculated until third render

I'm building a custom infinite scroll functional component in react, which can go in both directions, and am having some trouble because I need to calculate the scrollHeight and scrollWidth after the first items are loaded, which should be after the first render.

However, rather than getting the right value, I get the clientHeight even though the screen shows a scrollbar and that the size of the first child is far beyond the clientHeight, until the third render or the second effect call.

Here's the code showing the issue without the unnecessary logic, the layout effect doesn't log the full value until it ran a second time :

function InfiniteScroll({ children }) {
  const ref = useRef()
  
  console.log('render', ref?.current?.scrollHeight, children?.length)
  useLayoutEffect(() => {
    console.log('layout effect', ref?.current?.scrollHeight, children?.length)
  })

  return (
    <div ref={ref}>
      { children }
    </div>
}

Is there a way to get the full value on the first run? I'm assuming it has to do with having the render the children first to get the actual width? If that's the case, is there a way to run a useEffect hook after everything's been rendered?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source