Custom hooks (functions starting with use) encapsulate reusable stateful logic. To track mouse position, use useState to store coordinates and useEffect to add a mousemove event listener to the window. Crucially, the useEffect cleanup function must remove the listener to prevent memory leaks.

import { useState, useEffect } from 'react';
function useMousePosition() { const [position, setPosition] = useState({ x: 0, y: 0 }); useEffect(() => { const handleMove = (e) => setPosition({ x: e.clientX, y: e.clientY }); window.addEventListener('mousemove', handleMove); // Cleanup: Remove listener when component unmounts return () => window.removeEventListener('mousemove', handleMove); }, []); // Empty array: run effect only once on mount return position;
}
// Usage in component: const { x, y } = useMousePosition();