I'm trying to get the scrolling position. My code is working fine, but every time I scroll the function always rerenders the React component. I know the reason: every time I scroll I update the scroll position within the component's state.
export function Home() {
const [scrollPosition, setScrollPosition] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollPosition(window.scrollY);
};
handleScroll();
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
console.log('render function')
return null
}
Is there a way to optimize this code?