0

I am new to React and I am trying to understand how this piece of code works. I was following a tutorial and the author's code can be found on GitHub: https://github.com/judygab/web-dev-projects/blob/main/personal-portfolio/src/components/NavBar.js

I don't understand how this hook useEffect can continuously run even though it has an empty dependency array?

To my understanding, when you put an empty array as the second parameter, it will only fire off once, when the component is rendered to the DOM.

What exactly is happening so that it fires every time you scroll upon and down the page. I suspect that the definition I have is either not fully complete or the window.addEventListener is continuously adding/removing from the DOM.

  useEffect(() => {
    const onScroll = () => {
      if (window.scrollY > 50) {
        setScrolled(true);
        
      } else {
        setScrolled(false);
      }
    }

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

I have tried logging messages to the console at different points in the code but I am not sure why they would be firing continuously. Any explanation of what's going on would be greatly appreciated!

Dylan M
  • 3
  • 3
  • Try with useLayoutEffect. – Lansana Diomande Feb 20 '23 at 15:36
  • it means your component is being unmounted and mounted again – thedude Feb 20 '23 at 15:37
  • It will fire twice if you have react 18: https://stackoverflow.com/questions/72238175/why-useeffect-running-twice-and-how-to-handle-it-well-in-react – Erik Feb 20 '23 at 15:38
  • 3
    Is the effect actually being fired multiple times, or is it just the `onScroll` function you've added added to the scroll event? (The effect should run once, applying the event listener, but the event listener will repeatedly call `onScroll` when a scroll event occurs) – DBS Feb 20 '23 at 15:39
  • @DBS Reading your comment, I think I now understand. It's not that the `useEffect` is firing multiple times, it's that it creates a function `onScroll` and then sends that function to the window, which fires multiple times. That makes sense! Thank you all for the quick responses – Dylan M Feb 20 '23 at 15:53

1 Answers1

0

That's not true ,useEffect runs the code within it only once when you pass an empty deps array. You might have confused with onScroll handler that fires for every scroll point you on the UI.

Mallikarjun M G
  • 509
  • 4
  • 9