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>
);
};