Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Last active July 24, 2024 10:11
Show Gist options
  • Save icodeforlove/2ac02951a77ae9576a496a90feece923 to your computer and use it in GitHub Desktop.
Save icodeforlove/2ac02951a77ae9576a496a90feece923 to your computer and use it in GitHub Desktop.
ScrollRestoration for React
'use client';
import { useEffect } from 'react';
function ScrollRestoration() {
useEffect(() => {
const pushState = history.pushState;
history.pushState = function (data, unused, url) {
const scrollY = window.scrollY;
// Save the current scroll position in the state before navigating
history.replaceState({ ...history.state, _scrollY: scrollY }, '');
return pushState.call(history, data, unused, url);
};
const handlePopState = (event: PopStateEvent) => {
if (event.state?._scrollY) {
const scrollY = event.state._scrollY;
setTimeout(() => {
if (window.scrollY !== scrollY) {
window.scrollTo(0, scrollY);
}
}, 0);
}
};
window.addEventListener('popstate', handlePopState);
return () => {
history.pushState = pushState;
window.removeEventListener('popstate', handlePopState);
};
}, []);
return null;
}
export default ScrollRestoration;
@icodeforlove
Copy link
Author

This solution was tested with Next.js v15.

I encountered an issue where some components would cause the user to jump back to the top of the page when clicking the back button.

To resolve this, I monkey-patched the .pushState method. The patch runs a .replaceState to add a _scrollY position before executing the original .pushState.

When the user triggers a popState by going back, the script checks if the state being popped has a _scrollY property. If it does, it triggers a scrollTo on the next event loop.

This approach worked for me.

@LeakedDave
Copy link

IDK why but I'm testing this and it's scrolling the wrong page. Like I start on Page A, go to Page B, Scroll Down, go back to Page A, and Page A is scrolled down now

@icodeforlove
Copy link
Author

Are you using other things related to scroll?

This requires you to turn off all the scroll helpers as it will handle scroll positioning on its own.

Also this was only tested to work with pages with scrollbars on the main scroll (not sub elements, but could be adapted to do that as well).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment