Handle Sticky Header On Scroll
  • Work
    ,
  • About
    ,
  • Blog
    ,
  • Contact
Get In Touch
  • Home
  • Work
  • About
  • Blog
  • Contact

Developer & Designer

OreoGrapher © 2024
Published on: Sun Sep 15 2024
By - OreoGrapher
hook

Handle Sticky Header on Scroll

Handle Sticky Header on Scroll Image

Creating a sticky header that changes based on the user's scroll position is a common feature on modern websites. In this article, we'll break down a simple React implementation of this functionality using React hooks like useState and useEffect.

const [header, setheader] = useState(false);

useEffect(() => {
  window.onscroll = function () {
    if (window.scrollY > 130) {
      setheader(true);
    } else {
      setheader(false);
    }
  };

  return () => {
    window.removeEventListener("scroll", window.onscroll);
  };
}, []);

How It Works

useState Hook for State Management:
We initialize a piece of state called header with the value false using the useState hook. This state will determine whether or not the header has a "sticky" effect (i.e., when it's fixed to the top of the screen).

const [header, setheader] = useState(false);

useEffect Hook for Scroll Detection:
We then use the useEffect hook to detect when the user scrolls the page. This hook runs once when the component is mounted because we provide an empty dependency array ([]). Inside this hook, we set the onscroll event listener on the window object to trigger whenever the user scrolls.

useEffect(() => {
  window.onscroll = function () {
    if (window.scrollY > 130) {
      setheader(true);
    } else {
      setheader(false);
    }
  };
}, []);

Scroll Logic:
Every time the user scrolls, we check the scroll position using window.scrollY. If the scroll position is greater than 130 pixels, we set the header state to true, making the header sticky. Otherwise, we set it back to false.

if (window.scrollY > 130) {
  setheader(true);
} else {
  setheader(false);
}

Cleaning Up the Scroll Event:
To avoid potential memory leaks and ensure the event listener is properly removed when the component unmounts, we return a cleanup function that removes the scroll event listener.

return () => {
  window.removeEventListener("scroll", window.onscroll);
};

Application

This pattern is useful in scenarios where you want to toggle the appearance of a header or other UI elements based on how far down the page a user has scrolled. For instance, you could apply a different CSS class to the header when header is true to make it "stick" to the top.

Happy Coding ! </3

Leave a Comment

No comments yet

Similar Blogs

(0)