Updating React state in window.addEventListener

I have the following problem: I want to update a state when a scroll is happening.

I used the following solution:

React.useEffect(() => { window.addEventListener('scroll', scrollEvent) }, [])

My state is:

const [scrollAmount, setScrollAmount] = React.useState(0);

The event handler for my scroll event:

const scrollEvent = () => setScrollAmount(scrollAmount + 1);

The problem is my state doesn’t update. It’s quite understandable because I’m calling it just once without a re-render on the useEffect, but if I remove the [] of my useEffect, it will make it add even more scroll events, and I want just 1 scroll event that can update a state on window.

75 thoughts on “Updating React state in window.addEventListener”