Custom hook for detecting window.pageYOffset is not work as expected

Viewed 46

I have a hook which sets a boolean value to state if the window.pageYOffset is greater than 100

const useScrollPosition = () => {

  const [scrollPosition, setScrollPosition] = useState(false)

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('scroll', () =>
        setScrollPosition(window.pageYOffset > 100)
      )
    }
  }, [])

  return [scrollPosition]
}

export default useScrollPosition

Here is the application

          <Box
            display={displayScrollPosition ? 'none' : 'flex'}
            justifyContent="space-between"
            alignItems="center"
            border={'1px solid red'}
          >

If the boolean is true the container should disappear. The problem is in the UI. If I scroll quickly enough it flips cleanly. But if I keep my screen scrolled around 100 (window.pageYOffset) the boolean is flipping over and over and the component is showing and hiding very quickly and it looks like a glitch effect. Anyone experienced anything similar or can provide a possible solution?

1 Answers

Custom hook

import { useEffect, useState } from "react";

export const useScrollPosition = () => {
  const [scrollPos, setScrollPos] = useState(false);

  useEffect(() => {
    if (typeof window !== "undefined") {
      window.addEventListener("scroll", () => {
        if (window.pageYOffset > 100) {
          setScrollPos(true);
        }else{
          setScrollPos(false);
        }
      });
    }
  }, []);
  return { scrollPos };
};

App.js

import { useScrollPosition } from "your route custom hook";

export default function App() {
  const { scrollPos } = useScrollPosition();

  return (
   <div className="App">
      <Box
        display={scrollPos ? 'none' : 'flex'}
        justifyContent="space-between"
        alignItems="center"
        border={'1px solid red'}
      >
   </div>
  );
}
Related