Home > Software engineering >  window.scrollTo not working inside useEffect - reactJS
window.scrollTo not working inside useEffect - reactJS

Time:05-17

I am trying to execute window.scrollTo on the first render using useEffect function. I am storing the position inside localStorage, but it is not working.

Does not work on first page render:

useEffect(() => {
  window.scrollTo(0, localStorage.getItem('position'));
}, []);

It is worth noting that if I put the scroll function inside a function and call it through a button onClick it works.

This works if called from onClick:

const setScroll = () => {    
  window.scrollTo(0, localStorage.getItem('position'));
}

How can I solve it?

CodePudding user response:

When the useEffect function gets called the page hasn't been rendered, yet. Try calling window.scrollTo on the next frame:

useEffect(() => {
  setTimeout(() => window.scrollTo(0, localStorage.getItem('position')), 0);
}, []);
  • Related