Managing the position of a navigation bar on scroll is an essential feature in many web applications. This code snippet provides a custom React hook that monitors the scroll position of the window, useful for making dynamic UI adjustments such as changing the navbar's appearance during scroll.
The useScrollPosition hook leverages React's useState and useEffect to track and update the window's vertical scroll position. This behavior is key for creating responsive and interactive UI elements that depend on the user's scroll behavior.
Here's how you can define the useScrollPosition hook:
import { useEffect, useState } from 'react'; export const useScrollPosition = () => { const [scrollPosition, setScrollPosition] = useState(0); useEffect(() => { const updatePosition = () => { setScrollPosition(window.pageYOffset); }; window.addEventListener('scroll', updatePosition); updatePosition(); return () => window.removeEventListener('scroll', updatePosition); }, []); return scrollPosition; };
And here's an example of how you can use this hook in a component:
import { useScrollPosition } from "@/hooks/useScrollPosition"; const NavbarComponent = () => { const scrollPosition = useScrollPosition(); // Logic to modify navbar style based on scroll position could go here // Example: // const navbarClass = scrollPosition > 100 ? 'navbar-scrolled' : 'navbar'; return ( <nav /* className={navbarClass} */> {/* Navbar content here */} </nav> ); };
This hook offers a straightforward and efficient method for responding to scroll events within your React application. It's a building block for creating a dynamic and engaging user experience by adjusting the UI as the user scrolls through your content.
Disclaimer: This snippet is for educational purposes. Always ensure adequate testing before incorporating into a production environment.