useScrollPosition Hook

Get the current and previews scroll position of the browser window

Implementation

Interface
export interface IScrollPosition {
  x: number;
  y: number;
  prevX: number;
  prevY: number;
}
Utility-func
const isBrowser = typeof window !== 'undefined'

function getScrollPosition() {
  return isBrowser
    ? { x: window.pageXOffset, y: window.pageYOffset }
    : { x: 0, y: 0 };
}
Hook
import { useState, useEffect } from 'react';

export default function useScrollPosition() {
  const [position, setScrollPosition] = useState<IScrollPosition>({
    ...getScrollPosition(),
    prevX: getScrollPosition().x,
    prevY: getScrollPosition().y,
  });

  useEffect(() => {
    let requestRunning: null | number = null;

    function handleScroll() {
      if (isBrowser && requestRunning === null) {
        requestRunning = window.requestAnimationFrame(() => {
          setScrollPosition((prevScrollPosition) => {
            return {
              ...getScrollPosition(),
              prevX: prevScrollPosition.x,
              prevY: prevScrollPosition.y,
            };
          });
          requestRunning = null;
        });
      }
    }

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

  return position;
}

Make the space bigger

Get updates on what I do web development related. Early access to articles, easy-to-follow guides & tutorials, challenges, along with some other resources I'm reading and other stuff I think you'd enjoy...