title: React request animation frame for event listener mousemove
body: <p>I'm not sure how to implement <code>requestAnimationFrame</code> in this example as I always create an exponential infinite loop when trying it. I want the <code>mousemove</code> animation to be smooth that's why I want to use <code>requestAnimationFrame</code> but where should I set it. In my case I can't work with <code>useEffect</code>.
  In the Codesandbox, if you move your Mouse over the red background it should activate it the <code>mousemove</code> event.</p>
  <p>Codesandbox:
  <a href="https://codesandbox.io/s/late-dream-97bfhp?file=/src/RequestAnimationFrameTest.tsx:0-1307" rel="nofollow noreferrer">https://codesandbox.io/s/late-dream-97bfhp?file=/src/RequestAnimationFrameTest.tsx:0-1307</a></p>
  <p>Code:</p>
  <pre><code>import React, { useState, useRef } from &quot;react&quot;;
  
  const RequestAnimationFrameTest = () =&gt; {
    const [cursorPos, setCursorPos] = useState({ x: 0, y: 0 });
    const [cursorVisible, setCursorVisible] = useState(false);
    const requestRef = useRef();
  
    const handleMouseMove = (e) =&gt; {
      console.log(&quot;eventListener&quot;);
      const x = e.pageX;
      const y = e.pageY;
      setCursorPos({ x: x, y: y });
      // requestRef.current = requestAnimationFrame(handleMouseMove);
    };
  
    const handleMouseMoveRef = useRef(handleMouseMove);
  
    const handleMouseEnter = () =&gt; {
      document.body.style.cursor = &quot;none&quot;;
      addEventListener(&quot;mousemove&quot;, handleMouseMoveRef.current);
      setCursorVisible(true);
    };
  
    const handleMouseLeave = () =&gt; {
      document.body.style.cursor = &quot;default&quot;;
      removeEventListener(&quot;mousemove&quot;, handleMouseMoveRef.current);
      // cancelAnimationFrame(requestRef.current);
      setCursorVisible(false);
    };
    return (
      &lt;div className=&quot;container&quot;&gt;
        {cursorVisible &amp;&amp; (
          &lt;div
            style={{ top: cursorPos.y + &quot;px&quot;, left: cursorPos.x + &quot;px&quot; }}
            className=&quot;cursor&quot;
          &gt;
            Mouse
          &lt;/div&gt;
        )}
        &lt;div
          className=&quot;item&quot;
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
        &gt;&lt;/div&gt;
      &lt;/div&gt;
    );
  };
  </code></pre>