Search code examples
javascriptreactjssvgonmouseover

onMouseOver keeps calling when data changes


I have an application where I draw up to date locations on a map. These locations update about every second. I'm trying to have it so that I can hover over the locations, which are svg circles but onMouseOver keeps calling every time my useEffect updates the data and the locations on the map update. How can I fix this problem.

So basically I have an svg, which has a list of the following elemnts in:

const location = <circle
                     key = {'serialNumber'}
                     cx = {x}
                     cy = {y}
                     r = {4}
                     className="drone"
                     onMouseOver = {displayPilotName('name')}
                   />

And I draw that on a map. My useEffect works as following:

useEffect(() => {
  const interval = setInterval(() => {
  droneService.getAll().then(droneInfo =>
  setDrones(droneInfo))
  }, 500)
 return () => clearInterval(interval)
}, [])

I think the problem is because these two but might be cause by something else, but if I changed The interval to say 3 seconds it only called onMouseOver every 3 seconds. Also hover in css works fine, but I need to call an function from the hover so it doesn't work for this.


Solution

  • You are calling that function every render and passing whatever it returns... you should instead pass callback function

    const location = <circle
                         key = {'serialNumber'}
                         cx = {x}
                         cy = {y}
                         r = {4}
                         className="drone"
                         onMouseOver = {()=>displayPilotName('name')}
                       />
    

    this will be triggered only on mouseOver