I'm trying to scroll to a certain element in a react application, an empty div that sits on the end of the page. I'm trying to achieve this by using a Ref to track the div, and inside a useEffect() calling scrollTo on the div. Unfortunately it's not scrolling to the correct position - it should end up at the bottom of the page, but it only ends up part way down.
I have my suspicions why this is the case - an API call is made to receive data and populate a list, and I think it is scrolling to the point before the list is populated and thus makes the page bigger. What I don't get is that I have placed the scrolling code in a useEffect where the second parameter is the list state, so this should run after the list is populated. I've also tried replacing useEffect with useLayoutEffect but to no avail. The only thing I can think of is putting the scrolling code in a timer, but that seems atrocious. Am I missing something?
Simplified Example
const [messages, setMessages] = React.useState<string[]>([])
const endOfPageRef = useRef<HTMLDivElement>(null)
useEffect(() => {
apiCall().then(result => setMessages(result))
}, []);
useEffect(() => {
endOfPageRef.current?.scrollTo();
}, [messages])
return(
<div className="root">
<MessageList messages={messages}></MessageList>
<div ref={endOfPageRef}></div>
</div>
);
As stated previously, this ends up scrolling about a quarter way down the screen instead the desired behavior of to the bottom.