Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with useNavigate() hook and onWheel event

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")
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading