Restore scroll position in React Hooks with useRef is shaky

E

Emre

Guest
I want to scroll to my previous window position by setting inside a useEffect the window position back to its previous state. To get the previous state, I am using useRef.

The Component was once class-based and there it worked perfectly. After I refactored it to hooks, this "shaky" behavior started.

Declaring the useRef right at the beginning

const scrollRef = useRef(window.pageYOffset);


Whenever the component re-renders:

scrollRef.current = window.pageYOffset;


When the state gets updated:

useEffect(() => {
window.scrollTo(0, scrollRef.current)
});


The Complete Code:

export default () => {
const scrollRef = useRef(window.pageYOffset);
...
scrollRef.current = window.pageYOffset;
useEffect(() => {
window.scrollTo(0, scrollRef.current)
});

return (
...
);
}


On state update, I want to change back to the previous window position by not having this "shaky" behavior. (By shaky I mean it looks like he scrolls to the top and right after to the previous position so it looks like it shakes)

Continue reading...
 
Top