DeLe
DeLe

Reputation: 2480

React hooks - change state inside scroll event not working

I try to change myState inside scroll handle function like

const [myState, setMyState] = useState(false);
const refA = useRef(null)
const handle = (e) => {
    if (!myState) {
        console.log('Set', myState)
        setMyState(true);
    }else {
        console.log('no set')
    }
}
useEffect(() => {
    if (props.run) {
        const ref= refA.current
        ref.addEventListener("scroll", handle, { passive: true });
    }
}, [props.run]); 

useEffect(() => {
    const ref= refA.current
        return () => {
            ref.removeEventListener("scroll", handle, { passive: true });
        }
}, [])

return (
    <div ref={refA}>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
        <p>long</p><br/>
    </div>
);

But when i scroll my div, log is always show Set? myState can't change data? how to fix that thanks.

Upvotes: 0

Views: 548

Answers (1)

Viet
Viet

Reputation: 12777

Just add myState in the useEffect. And add removeEventListener in return of this useEffect, don't need create other useEffect

useEffect(() => {
  if (props.run) {
    const ref = refA.current;
    ref.addEventListener("scroll", handle, { passive: true });
    return () => {
      ref.removeEventListener("scroll", handle, { passive: true });
    };
  }
}, [props.run, myState]);

Add myState in the dependencies will call useEffect when this state change. And the variable in the handle will be updated with new state.

You should return removeEventListener after call addEventListener to make sure when useEffect call again, the old event will be removed.

Upvotes: 1

Related Questions