DEV Community

Cover image for Save scroll state in React when visiting an other page with a custom hook
Adi
Adi

Posted on

Save scroll state in React when visiting an other page with a custom hook

The problem:

Saving scroll state is very a important for a good user experience especially when the page in your React web application is really long and has a lot of content. It can be quite annoying when a user visits another page and comes back to the previous page only to find out that they have to scroll from the top of the page all over again. Well we can save them this pain by adding a little code that saves the scroll position of the page the user was at before.

Lets create custom hook in useScrollPosition.js

import {useEffect} from "react";

// Object in which we will save our scroll position state
const scrollPositions = {};

/* custom hook which will save the scroll state and also set 
the scroll position of our page */
const useScrollPosition = (page) => {

    useEffect(() => {

// Get the scroll state if it exists

        const pageScrollPosition = scrollPositions[page];

// If it exists then set the scroll position of our page

        if (pageScrollPosition) {

/* Using setTimeout to set the scroll position of the 
page as useEffect gets triggered before the page has 
actually rendered */

            setTimeout(() => {
                window.scrollTo(0, pageScrollPosition);
            }, 50)

        }

/* save function to save the scroll position in 
the scrollPositions object */

        const save = () => {
            scrollPositions[page] = window.scrollY;
        }

/* Attaching an event listener to listen for a scroll event 
and then fire the save function everytime a scroll event occurs */

        window.addEventListener('scroll', save)

/* Removing the event listener when the component unmounts*/

        return () => {
            window.removeEventListener('scroll', save)
        };
    }, [page]);
}

export default useScrollPosition;

Enter fullscreen mode Exit fullscreen mode

Now use the useScrollPosition hook in your component where you want to save the scroll state:

import useScrollPosition from "./useScrollPosition";

// Call the useScrollPosition hook with the page name

useScrollPosition("Home")
Enter fullscreen mode Exit fullscreen mode

That's it! We're all done!

all done gif

Top comments (0)