Search code examples
javascriptreactjsnext.jsmouseevent

React onMouseEnter and onMouseLeave bug, not working consistently


I am having issues with React onMouseEnter and onMouseLeave, sometimes the events are not firing when it should

I am using onMouseEnter and onMouseLeave to show/hide a React Portal Modal tooltip panel:

enter image description here

enter image description here

the issue:

if the mouse cursor hovers over the images slowly, onMouseEnter and onMouseLeave works as expected, but if the mouse cursor hovers over the image rapidly ( horizontally ), the code breaks, and multiple tooltip panels are shown ( because onMouseLeave failed to trigger )

here is the video link showing the issue: https://www.veed.io/view/7669d6c4-6b18-4251-b3be-a3fde8a53d54?sharingWidget=true

here is the codesandbox link for bug I mentioned: https://codesandbox.io/s/epic-satoshi-rjk38e

any help is appreciated


Solution

  • The cause for the "lost events" is not the event listeners not firing. The problem is that you mix React code, which operates on the virtual DOM, with "classical" JS code, which operates on the browser DOM. These two DOMs are out-of-sync most of the time, which causes the hiccups that you see.

    Try to remove all code that directly accesses the DOM and operate on React components (i.e. in the virtual DOM) only.

    Here is an stripped-down example how to implement your tooltip in React-only style:

    https://codesandbox.io/s/musing-villani-c0xv24?file=/src/App.js