useScrollRestoration

A hook to restore scroll positions when navigating back to a page.

import { useScrollRestoration } from 'react-sprout';

let [mainRef, sidebarRef] = useScrollRestoration();

The hook returns an array of react refs that you can attach to elements whose scroll position needs to be restored after navigation. You can destructure as many as you need.

function Page() {
	let [mainRef, sidebarRef] = useScrollRestoration();

	return (
		<>
			<main ref={mainRef} style={{ overflow: 'auto' }}>
				...
			</main>
			<aside ref={sidebarRef} style={{ overflow: 'auto' }}>
				...
			</aside>
		</>
	);
}

The useScrollRestoration hook also takes a boolean that is used to indicate if the window scroll position needs to be restored too.

  • Name
    restoreWindow
    Type
    boolean
    Description

    A boolean indicating whether to restore the window scroll position too.

import { useScrollRestoration } from 'react-sprout';

let [elementRef] = useScrollRestoration(true);

This will restore both the element with the elementRef and the window scroll position.