1

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?

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
Riky Andreas
  • 220
  • 3
  • 13
  • Try throttling/debouncing your handler, it will reduce some re-renders. You can also give this a look: https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate Related: https://stackoverflow.com/a/56297625/11613622, https://stackoverflow.com/q/54666401/11613622 – brc-dd Aug 13 '21 at 17:30

1 Answers1

2

Consider using this custom hook. I used it and it's super optimized. https://github.com/n8tb1t/use-scroll-position