Tweak useScrollDirection behavior
This commit is contained in:
parent
4a8964f520
commit
d04488982a
@ -1,21 +1,22 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
|
||||
export default function useScrollDirection() {
|
||||
const [scrollInfo, setScrollInfo] = useState({
|
||||
scrollDirection: 'down' as 'up' | 'down',
|
||||
lastScrollY: 0,
|
||||
});
|
||||
const [scrollDirection, setScrollDirection] =
|
||||
useState<'up' | 'down'>('down');
|
||||
|
||||
const lastScrollY = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
setScrollInfo(prev => ({
|
||||
scrollDirection: window.scrollY > prev.lastScrollY ? 'down' : 'up',
|
||||
lastScrollY: window.scrollY,
|
||||
}));
|
||||
setScrollDirection(window.scrollY > lastScrollY.current ? 'down' : 'up');
|
||||
lastScrollY.current = window.scrollY;
|
||||
};
|
||||
window.addEventListener('scroll', handleScroll);
|
||||
return () => window.removeEventListener('scroll', handleScroll);
|
||||
}, []);
|
||||
|
||||
return scrollInfo;
|
||||
return {
|
||||
scrollDirection,
|
||||
lastScrollY: lastScrollY.current,
|
||||
};
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user