React Hook: Detect Scroll Direction

 by Robin Wieruch
 - Edit this Post

A neat that I used in some of my which detects the scroll direction of a user:

import * as React from 'react';
const THRESHOLD = 0;
const useScrollDirection = () => {
const [scrollDirection, setScrollDirection] = React.useState('up');
const blocking = React.useRef(false);
const prevScrollY = React.useRef(0);
React.useEffect(() => {
prevScrollY.current = window.pageYOffset;
const updateScrollDirection = () => {
const scrollY = window.pageYOffset;
if (Math.abs(scrollY - prevScrollY.current) >= THRESHOLD) {
const newScrollDirection =
scrollY > prevScrollY.current ? 'down' : 'up';
setScrollDirection(newScrollDirection);
prevScrollY.current = scrollY > 0 ? scrollY : 0;
}
blocking.current = false;
};
const onScroll = () => {
if (!blocking.current) {
blocking.current = true;
window.requestAnimationFrame(updateScrollDirection);
}
};
window.addEventListener('scroll', onScroll);
return () => window.removeEventListener('scroll', onScroll);
}, [scrollDirection]);
return scrollDirection;
};
export { useScrollDirection };

In a , the custom React hook can be used this way:

import * as React from 'react';
import { useScrollDirection } from './useScrollDirection';
const App = () => {
const scrollDirection = useScrollDirection(ref);
console.log('up');
return (...);
};

That's it. There may be many ways to improve this custom hook (e.g. check the horizontal instead of the vertical scroll direction), but for my cases it has been sufficient for now.

Keep reading about 

A neat custom React Hook that I used in some of my React freelance projects which checks if an element's content has overflow (here: vertical overflow): If you want to detect a horizontal…

If you are wondering how to run React's useEffect Hook only on update , you may be surprised that you need React's useRef Hook as helper to create an instance variable for tracking the component's…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.