0

I am currently trying to create a piece of code that will mode a div when the user scrolls past a certain place. to do this i used window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection)) where i pass both of the variables returned from React.useState(0), then from within the event listener i check to see if the window.scrollY property is more than the value in the scrollSection state and if so translate it with js. but no matter what i do the function provided to update the state isnt updating the state, its not slow its just not updating at all. I was wondering if this is because i passed it into an event listener?

Event Listener and useState Initialization

function SideNav(props: any) {
  const [scrollSection, setScrollSection] = React.useState(0);
  React.useEffect(() => {
    window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection));

    return () => {
      window.removeEventListener('scroll', () => checkSection(scrollSection, setScrollSection));
    };
  }, []);

Function passed to event listener

function checkSection(scrollSection: number, setScrollSection: Function){
  let scrollSections = [0, 1538, 2583, 2089, 3089]
  const scrollY = window.scrollY;
  setScrollSection(1);
  console.log("scroll Y: "+scrollY);
  console.log("section: "+scrollSection)
}
Darcy Power
  • 195
  • 12
  • 2
    Two issues: 1. That isn't how you remove an event listener. You have to use the **same function**, not an equivalent function, in the call to `removeEventListener`. 2. Your event listener closes over the **first** version of `scrollSection`, not the updated version later calls to your component function see. – T.J. Crowder Dec 03 '22 at 15:15
  • Do you get any errors when you try to implement this? – Farbod Shabani Dec 03 '22 at 15:15
  • @T.J.Crowder i got the code to add the event listener online and don't understand much about them including the correct way to remove one, would i accomplish this by first saving `() => checkSection(scrollSection, setScrollSection)` in a variable and passing that to the `window.addEventListener` and `window.closeEventListener`? also I'm not sure how to fix the second problem you listed. – Darcy Power Dec 06 '22 at 16:41
  • 1
    @DarcyPower - Do `const handler = () => checkSection(scrollSection, setScrollSection);`, then use `handler` both in the `addEventListener` call and the `removeEventListener` call. – T.J. Crowder Dec 06 '22 at 16:43

1 Answers1

1

setState is asynchronous. you will not see the updated value immediately after setting the value. use useEffect to catch the updated values

useEffect(() => {
  console.log("section: "+scrollSection)

}, [scrollSection])
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • Stale state is ***very*** well-covered by previous questions and answers. Better to find the earlier question than to post Yet Another Answer to the same question. – T.J. Crowder Dec 03 '22 at 15:17