Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

window.scrollTo not working inside useEffect – reactJS

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This works if called from onClick:

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

How can I solve it?

>Solution :

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);
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading