UPD: проблему решил. код обновил.
Состояние:
const [scrollPosition, setScrollPosition] = useState({
scrollX: 0,
scrollY: 0,
});
Обработчик клика:
const getCurrentScrollPosition = (e) => {
let cordsAfterClick = {};
let cords = ["scrollX", "scrollY"];
cords.forEach((cord) => {
cordsAfterClick[cord] = window[cord];
});
console.log("Obj with cords: ", cordsAfterClick);
localStorage.setItem("scrollCord", JSON.stringify(cordsAfterClick));
};
useEffect:
useEffect(() => {
setScrollPosition((prevScrollCord) => {
return {
...prevScrollCord,
...JSON.parse(window.localStorage.getItem("scrollCord")),
};
});
window.scrollTo(scrollPosition.scrollX, scrollPosition.scrollY);
}, [scrollPosition.scrollX, scrollPosition.scrollY]);