Home > Software engineering >  Problem with useNavigate() hook and onWheel event
Problem with useNavigate() hook and onWheel event

Time:09-11

I need to switch routes with the onWheel event. If the deltaY property of the onWheel event > 0, I call the useNavigate hook to change the route. The problem is that when going back the route changes as many times as I turn the mouse wheel. How do I fix this bug?

const navigate = useNavigate()

const handleWheel = (e) => {
    e.deltaY > 0 && navigate("/newRoute")
}

CodePudding user response:

Mouse wheel and scroll events are notoriously noisy. Try to remove the event listener when the condition is met, or set some "state" that it's been "handled" so only 1 navigation action is triggered.

Example:

const navigateRef = React.useRef();
const navigate = useNavigate();

const handleWheel = (e) => {
  if (e.deltaY > 0 && !navigateRef.current) {
    navigateRef.current = true;
    navigate("/newRoute");
  }
}
  • Related