A simple, performant, and cross-browser hook for handling scroll in your next react app.
npm i use-scroll-direction
The hook returns the object with the actual scroll direction which could be one of three states: 'NONE', 'DOWN', 'UP', and useful booleans.
import {useScrollDirection} from "use-scroll-direction";
export const WindowExample = () => {
const {
scrollDirection,
isScrolling,
isScrollingUp,
isScrollingDown
} = useScrollDirection();
useEffect(() => {
console.log(scrollDirection)
}, [scrollDirection]);
return (
<div>{...}</div>
)
};
import {useScrollDirection} from "use-scroll-direction";
export const ComponentRefExample = () => {
const elementRef = useRef(null);
const {scrollDirection} = useScrollDirection({ref: elementRef});
useEffect(() => {
console.log(scrollDirection)
}, [scrollDirection]);
return (
//The content needs to overflow a container
<div ref={elementRef} style={{height: '100vh', overflowY: 'scroll'}} >
<div>{...}</div>
</div>
)
};
Name | Type | Description |
---|---|---|
wait |
?number |
Time in ms for throttling of scroll handler (default: 50) |
timeToReset |
?number |
Time in ms after last scroll event to reset the state (default: 250) |
ref |
?string |
When passed, the listener will be attached to element instead of window object |