Implement component encapsulation using React hooks

1. Custom hook

import React, { useEffect, useState } from 'react';

Create a function component: Note the custom hook naming convention
const useMousePosition = () = > {
    // 2. Define the initial value of state and the function to modify state
    const [positions, setPosition] = useState({ x: 0.y: 0 });

    useEffect(() = > {
        const updateMouse = (e: MouseEvent) = > {
            // 4. Reassign positions to change mouse position
            setPosition({ x: e.clientX, y: e.clientY });
        };
        // 3. Monitor mouse movement
        document.addEventListener("mousemove", updateMouse);
        return () = > {
            // Remove the mouse movement event
            document.removeEventListener("mousemove", updateMouse); }}, [])// Return to mouse position
    return positions;
};

export default useMousePosition;
Copy the code

2. Use custom hooks

import useMousePosition from "./hooks/useMousePosition";

function App() {
    const positions = useMousePosition();
 
    return (
        <p>x: {positions.x}, y: {positions.y}</p>)}Copy the code

Hook is so interesting!!