qol-hooks
Version:
A collection of React hooks to improve the quality of life of developers.
39 lines (38 loc) • 947 B
JavaScript
import { useEffect, useState } from "react";
/**
* Custom hook that tracks the scroll position of the window.
* @returns {number} The current scroll position in pixels.
*
* @example```tsx
* const Component = () => {
* const scrollPosition = useScroll();
*
* return (
* <div>
* <p>Scroll Position: {scrollPosition}</p>
* </div>
* )};
* ```
*/
function useScroll() {
const [scrollPosition, setScrollPosition] = useState({
x: 0,
y: 0,
});
useEffect(() => {
if (typeof window === "undefined")
return;
const handleScroll = () => {
setScrollPosition({
x: window.scrollX,
y: window.scrollY,
});
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return scrollPosition;
}
export default useScroll;