See what's launched

The next gen Gatsby is here Performance, developer velocity, and scaling to meet Enterprise needs - See what’s launched

Scroll Restoration

Scroll restoration refers to the scrollRestoration property on the History API. This property allows restoring a user’s scroll position when navigating to a new page.

Gatsby will handle scroll restoration for you in most cases. However, when you render containers that have their own scroll values, those scroll positions are typically lost between page transitions. To solve that, users can use the useScrollRestoration hook in their code to tell Gatsby about scroll containers that we should track and restore.

Here is an example of using the useScrollRestoration hook to render a list of countries in an overflow ul element.

The string page-component-ul-list is an arbitrary key. It should be unique for the page you are using it in. It is stored in the browser’s Storage > Session Storage with a key consisting of @@scroll/your-page-name/your-key. You can access it in your Chrome developer tools and you will see that it simply records the y offset of the scroll bar for that widget, for that page. Therefore, if you navigate to another page, the scroll bar for the targeted component will return to where it was the last time you visited that page during the current session.

useScrollRestoration is part of the gatsby-react-router-scroll package.

Edit this page on GitHub
© 2022 Gatsby, Inc.