Skip to content
Advertisement

Reactjs: Why doesn’t state boolean lock on event listener?

React Noob – thought I’d ask here for a quick answer before I spend hours digging.

In the example below I have an event listener inside useEffect that listens for scroll position on a container and fires a trigger after a point if it hasn’t done so already.

I want to know why the event still triggers even though the boolean registers true in the DOM. I’ve solved the problem by using a normal variable but I think it would benefit me to understand why this is happening. I’ve read lightly into mutating states and have experimented with changing the useState to an object like useState({status: false}) but this had similar results.

Even a point in the direction of a reading topic would be enough. Cheers!

JavaScript
JavaScript
JavaScript

Advertisement

Answer

You have:

JavaScript

So every time stateBool changes, you call addEventListener – adding a new scroll handler. For the more predictable output you’re expecting, remove the previous scroll handler in the effect cleanup.

JavaScript

JavaScript
JavaScript
JavaScript

But, a better approach would be to use the onScroll prop for the container – best to only use vanilla DOM methods like addEventListener when there no reasonable way to achieve the same results through React.

JavaScript
JavaScript
JavaScript
Advertisement