DEV Community

Cover image for Save scroll state in React when visiting another page
Adi
Adi

Posted on • Updated on

Save scroll state in React when visiting another page

The problem:

Saving scroll state is very 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.

Create two separate functions as follows:

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

// Function to save the scroll state
export const saveState = (page, object) => {
    state[page] = object
}

// Function to get the scroll position state
export const getState = (page) => {
    return state[page]
}
Enter fullscreen mode Exit fullscreen mode

In the main component where you want to retain the scroll position add the following code:


import {getState, saveState} from "./Util";

// Get stored scroll position state
const scrollPoint = getState('scrollState')
const scrollY = scrollPoint?.scrollY

/* useEffect to get and set the scroll position in the 
current page */
useEffect(() => {
    if (scrollY) {

/* setTimeout used to set the scroll position as the
useEffect triggers before the actual page renders */
        setTimeout(() => {
            window.scrollTo(0, scrollY);
        }, 50)
    }
}, [scrollY])

// useEffect to store the scroll position in the current page 
useEffect(() => {
    const save = () => {
        saveState('scrollState', {
// accessing the vertical scroll position in the window object
            scrollY: window.scrollY
        })
    }

/* Firing the save function whenever the event listener 
picks up a scroll event */
    window.addEventListener('scroll', save)
    return () => window.removeEventListener('scroll', save)

}, [])
Enter fullscreen mode Exit fullscreen mode

You can also use this separately as a custom hook and then use it in every component/page where you intend to save the scroll position. See here in my other article where I use the same logic in a custom hook.

There you go, you have now successfully set the scroll state of your component.

Top comments (1)

Collapse
 
renegadedev profile image
Adi

This is an even better solution cheers !