2

Inside a component I need to know if the browser has a mouse or not, it affects the component.

My plan is to listen for global mousemoves, but I'm not sure how I should do this in react. I could do something like this inside the component:

window.addEventListener('mousemove', onMouseMove, false);

but I'm not sure if it's a good idea. The component will be used lot's of times on the same page, so maybe I should put it in a component of it's own somehow?

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • 1
    You can create one non react object with event listener and then pass data to you components via props – Oleg Pro Dec 24 '16 at 09:28

1 Answers1

1

In the JavaScript world, there isn't a reliable way to catch if the user has a mouse or not. There are related discussions on this topic in a few places. But you already know that.

Having this in mind, I see two important considerations in order to not cause performance issues while implementing your plan to listen for global mousemoves.

  1. Kill the event listener immediately after it executes the first time.

    let hasMouse = false;
    
    const hasMouseCheck = () => {
        hasMouse = true;
    
        // Kill the event listener, so it executes only once
        window.removeEventListener('mousemove', hasMouseCheck, false);
    };
    
    window.addEventListener('mousemove', hasMouseCheck, false);
    
  2. Put your logic in a place where it will execute only once, when your application loads. A good place is the componentDidMount lifecycle hook on your entry (main) component. That's a method invoked only once, immediately after the component is mounted. From there on, pass it to whichever component you need.

    Or, of course, you could just place the above snippet in an external javascript file (without creating a ReactJS component), and set the hasMouse flag in the global window scope. Then, access it via window.hasMouse from whichever component you need, again.

    Implement the approach that makes the most sense to you for your specific use-case. The important thing is to make sure the logic executes only once ;-)

Community
  • 1
  • 1
Kaloyan Kosev
  • 12,483
  • 8
  • 59
  • 90