- Published on
useWindoScroll Hook React

useWindoScroll Hook React
useWindoScroll Code and Usage
useWindoScroll is a hook used to track the current scroll position of the window. It's particularly useful when you want to respond to the users scrolling behavior and perform certain actions based on the scroll position.
import { useState, useEffect } from "react";
const useWindowScroll = () => {
const [scrollPosition, setScrollPosition] = useState({ x: 0, y: 0 });
const handleScroll = () => {
setScrollPosition({ x: window.scrollX, y: window.scrollY });
};
useEffect(() => {
// Add scroll event listener when the component mounts
window.addEventListener("scroll", handleScroll);
// Remove scroll event listener when the component unmounts
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []); // Empty dependency array ensures the effect runs only once on mount
return scrollPosition;
};
// Usage
const WindowScrollExample = () => {
const { x, y } = useWindowScroll();
return (
<div>
<p>Scroll position:</p>
<p>X: {x}</p>
<p>Y: {y}</p>
</div>
);
};