Get scroll position with Reactjs

In case you need to keep on track of the scroll position, you can use react hooks to do so, that way it’s possible to check the scroll position any time you need it:

import React, { useState, useEffect } from 'react';

// inside component:

const [scrollPosition, setScrollPosition] = useState(0);
const handleScroll = () => {
    const position = window.pageYOffset;

useEffect(() => {
    window.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
        window.removeEventListener('scroll', handleScroll);
}, []);

In this case useEffect will behavior similar to componentDidMount, it will fire once the component has rendered, but also in every render, as Jared Beach commented bellow: “window.addEventListener is smart enough to discard subsequent calls with the same parameters”. . Make sure to return the cleanup function, similar to what you’d do in componentWillUnmount.

Leave a Comment