This post is mirrored on my blog, chrisfrew.in.

In a recent project, I was tasked with maintaining scroll position between pages. At first, I was certain the solution would have to be a complex one, where we would have to listen to scroll event listeners (always a critical task in terms of performance and efficiency), and share a complex state of various page scroll positions (the value of window.scrollY) for everything to work properly.

In the end, leveraging both localStorage and some advanced abilities of React hooks resulted in a rather elegant solution.

I’m happy to share it with you.

Let’s go!

Requirements

  1. First, we need to remember the window.scrollY value per page - this can be solved with localStorage. We’ll pass a page key to identify which localStorage variable has the scrollY value we need to rehydrate.
  2. We only need to store the scroll position when the user leaves that page. This is where I realized that there was no event listener required. No need to listen to the scroll event to complete this functionality! (Already a huge plus). The ‘trick’, if you will, is leveraging React’s useEffect return value, which can be a function, i.e., a useEffect call can have the following form:
useEffect(() => {
    // ...some effect code here...
    return () => {
        // this code fires on unmount! Perfect for our use case!
    }
})
  1. Finally, and maybe the most tricky one: we should only rehydrate the page scroll position after the full content for the page has loaded. For example, if we are loading a bunch of tiles or pictures (or anything really that ends up in the DOM) from an async process, we wait to make sure that data is set in the DOM before restoring our scrollY position. Therefore, our hook should also be able to accept a parameter which is boolean type. I called it setCondition. We’ll only call window.scrollTo if that setCondition variable is true.

#typescript #software-development #javascript #react #react-hook #react native

Persist and Remember Page Scroll Position, i.e. window.scrollY Using React Hooks
3.00 GEEK