Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
React request animation frame for event listener mousemove

I'm not sure how to implement requestAnimationFrame in this example as I always create an exponential infinite loop when trying it. I want the mousemove animation to be smooth that's why I want to use requestAnimationFrame but where should I set it. In my case I can't work with useEffect. In the Codesandbox, if you move your Mouse over the red background it should activate it the mousemove event.

Codesandbox: https://codesandbox.io/s/late-dream-97bfhp?file=/src/RequestAnimationFrameTest.tsx:0-1307

Code:

import React, { useState, useRef } from "react";

const RequestAnimationFrameTest = () => {
  const [cursorPos, setCursorPos] = useState({ x: 0, y: 0 });
  const [cursorVisible, setCursorVisible] = useState(false);
  const requestRef = useRef();

  const handleMouseMove = (e) => {
    console.log("eventListener");
    const x = e.pageX;
    const y = e.pageY;
    setCursorPos({ x: x, y: y });
    // requestRef.current = requestAnimationFrame(handleMouseMove);
  };

  const handleMouseMoveRef = useRef(handleMouseMove);

  const handleMouseEnter = () => {
    document.body.style.cursor = "none";
    addEventListener("mousemove", handleMouseMoveRef.current);
    setCursorVisible(true);
  };

  const handleMouseLeave = () => {
    document.body.style.cursor = "default";
    removeEventListener("mousemove", handleMouseMoveRef.current);
    // cancelAnimationFrame(requestRef.current);
    setCursorVisible(false);
  };
  return (
    <div className="container">
      {cursorVisible && (
        <div
          style={{ top: cursorPos.y + "px", left: cursorPos.x + "px" }}
          className="cursor"
        >
          Mouse
        </div>
      )}
      <div
        className="item"
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      ></div>
    </div>
  );
};
about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!