React Basics~useEffect/ Pointer Animation~



This content originally appeared on DEV Community and was authored by Ogasawara Kakeru

・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 (
    <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;

・This component dispalys a pointer follows the mouse pointermoving.

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

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

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

・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;

・This component displays the Pointer componnet.

Image description


This content originally appeared on DEV Community and was authored by Ogasawara Kakeru