I want to get the current y position in de document to change the ui at certain moments.
The code I use atm doesn't work and I don't get why.
const [verticalPosition, setVerticalPosition] = useState()
useEffect(() => {
setVerticalPosition(window.scrollY)
}, [window.scrollY])
useEffect(() => {
console.log(verticalPosition)
}, [verticalPosition])
I've searched for alternatives and found the most complex libraries to do something just that easy. So I would want to make it work this way. Could someone tell me how this could get working?
Thanks in advance
You need to add an event listener to the document.scroll event like so:
const [verticalPosition, setVerticalPosition] = useState()
useEffect(() => {
const onScroll = ()=>{
setVerticalPosition(window.scrollY);
}
document.addEventListener('scroll', onScroll);
return ()=>document.removeEventListener('scroll', onScroll); // cleanup function runs when component is unmounted
}, []); // empty dependency array so it only runs on mount
If you need this behavior in multiple components, this is trivial to abstract into a custom hook:
// hooks/useScrollY.js
const useScrollY = ()=>{
const [verticalPosition, setVerticalPosition] = useState()
useEffect(() => {
const onScroll = ()=>{
setVerticalPosition(window.scrollY);
}
document.addEventListener('scroll', onScroll);
return ()=>document.removeEventListener('scroll', onScroll);
}, []);
return verticalPosition;
}
export default useScrollY;
// how to use:
import useScrollY from "../hooks/useScrollY"
const MyComponent = ()=>{
const scrollY = useScrollY();
// do something with scrollY
return (
//...
);
}