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;
@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