Last active
January 8, 2024 13:44
-
-
Save joshuacerbito/ea318a6a7ca4336e9fadb9ae5bbb87f4 to your computer and use it in GitHub Desktop.
Custom React hook for listening to scroll events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* useScroll React custom hook | |
* Usage: | |
* const { scrollX, scrollY, scrollDirection } = useScroll(); | |
*/ | |
import { useState, useEffect } from "react"; | |
export function useScroll() { | |
const [lastScrollTop, setLastScrollTop] = useState(0); | |
const [bodyOffset, setBodyOffset] = useState( | |
document.body.getBoundingClientRect() | |
); | |
const [scrollY, setScrollY] = useState(bodyOffset.top); | |
const [scrollX, setScrollX] = useState(bodyOffset.left); | |
const [scrollDirection, setScrollDirection] = useState(); | |
const listener = e => { | |
setBodyOffset(document.body.getBoundingClientRect()); | |
setScrollY(-bodyOffset.top); | |
setScrollX(bodyOffset.left); | |
setScrollDirection(lastScrollTop > -bodyOffset.top ? "down" : "up"); | |
setLastScrollTop(-bodyOffset.top); | |
}; | |
useEffect(() => { | |
window.addEventListener("scroll", listener); | |
return () => { | |
window.removeEventListener("scroll", listener); | |
}; | |
}); | |
return { | |
scrollY, | |
scrollX, | |
scrollDirection | |
}; | |
} |
Hi,
Really nice what you all did above, my question is the first post made by @joshuacerbito is the updated version after all comments made by the community or anyone came with let's say a "better solution".
Thanks 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only register 'scroll' event one time: