DEV Community

Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React Basics~useEffect/ Pointer Animation~

・src/components/Pointer.tsx

import { useEffect, useState } from "react";

const Pointer = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  function handleMove(e) {
    setPosition({ x: e.clientX, y: e.clientY });
  }

 useEffect(() => {
    window.addEventListener("pointermove", handleMove);

    return () => {
      window.removeEventListener("pointermove", handleMove);
    };
  }, []);

  return (
    <div
      style={{
        position: "absolute",
        backgroundColor: "blue",
        borderRadius: "50%",
        opacity: 0.6,
        pointerEvents: "none",
        transform: `translate(${position.x}px, ${position.y}px)`,
        left: -20,
        top: -20,
        width: 50,
        height: 50,
      }}
    ></div>
  );
};

export default Pointer;
Enter fullscreen mode Exit fullscreen mode

・This component displays a pointer that follows the movement of the mouse pointer.

・The function of the window object, in this case it is the addEventListener, is one of the side effects.

・The side effects should be used in useEffect, as you can see in this snippet below.

 useEffect(() => {
    window.addEventListener("pointermove", handleMove);
  }, []);
Enter fullscreen mode Exit fullscreen mode

・You should call the cleanup function, which is called when the component is unmounted, to remove eventLisner in this snippet below.

 return () => {
    window.removeEventListener("pointermove", handleMove);
  };

Enter fullscreen mode Exit fullscreen mode

・src/App.tsx

import "./App.css";
import Pointer from "./lessons/Lesson2/Lesson2_1/Pointer";

function App() {
  return (
    <div className="flex items-center max-w-4xl mx-auto py-8 text-2xl">
      <Pointer />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

・This component displays the Pointer componnet.

Image description

Top comments (0)