0

I have a homepage where user's feed is shown. When user clicks on one of the feed card it goes to a different url, when user comes back to the homepage, it scrolls to top. I want to preserve the scroll position of the homepage so user can continue scrolling from previous scroll position.

I tried to use this method https://stackoverflow.com/a/67124040/14786214 but it does not work on Router v6

Billjesh Baidya
  • 189
  • 1
  • 12

2 Answers2

3

Create a component to manage the feed's state, e.g. stateSaver.js:

const state = {}

export const saveState = (component, object) => {
    
    state[component] = object
    
}

export const getState = (component) => {
    
    return state[component]
    
}

Then, within your feed.js, retreive the scroll position and use a listener to update it:

import { getState, saveState } from './stateSaver';

useEffect(() => {
        
    if(getState('Feed')){
     
        let { scrollY } = getState('Feed')
        
        window.scrollTo(0, scrollY), 200)
        
    }
    
}, [])


useEffect(() => {
    
    const save = () => {
        
        saveState('Feed', {  scrollY: window.pageYOffset  })        
        
    }
    
    save()
    
    document.addEventListener('scroll', save)
    
    return () => document.removeEventListener('scroll', save)
    
}, [])

The solution works assuming that you are working with a single web application.

Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36
0

What @Erik Martín Jordán gave as a solution works but the first useEffect will not trigger at the right time when the page loads, also I dont know why the 200 is required in the scrollto. the following solution can work better for it as we are using setTimeout to delay the scroll action happening by 50 ms and also using scrollY in dependancy array for the useEffect:

import { getState, saveState } from './stateSaver';

const { scrollY } = getState('Feed')


useEffect(() => {   
    if(scrollY){
    setTimeout(() => {
            window.scrollTo(0, scrollY);
        },50)
    
}
}, [scrollY])



useEffect(() => {
    const save = () => {
    saveState('Feed', {  scrollY: window.pageYOffset  })        
    
}

save()

document.addEventListener('scroll', save)

return () => document.removeEventListener('scroll', save)
}, [])