Back to snippets

Check Navbar position on scroll

Snippet Overview

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.

Snippet Explanation

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.

Code

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> ); };

Usage

  • Import and call the useScrollPosition hook within your navbar component file.
  • Use the scrollPosition value returned from the hook to conditionally render styles, classes, or other components.

Features

  • Reusability: This hook is designed to be reused across different components or projects.
  • Performance: The event listener is properly cleaned up to prevent memory leaks.
  • Flexibility: The hook's logic can be easily extended for more complex requirements or to track additional aspects of scrolling.

Conclusion

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.