Search code examples
reactjsuse-effect

Working of useEffect hook in react.js. Problem in dependency array part of useEffect


I have little confusion on how use effect works.

 const recordMouse = e => {
      setX(e.clientX)
      setY(e.clientY)
 }
 useEffect(() => {
      window.addEventListener('mousemove',recordmouse)  
 },[])

When we provide an empty dependency array the useEffect run on first render, if I'm not wrong, but here I found that I was getting every mouse position. Can somebody explain what's happening.


Solution

  • There is only one mouseover event binding, but the callback(recordMouse) is executed every time the mouseover is triggered.

    It has nothing to do with useEffect, you can try it with vanilla javascript.