Optimize FancyCursor by replacing elementFromPoint with event delegation
This commit is contained in:
@@ -19,6 +19,11 @@ export const FancyCursor = memo(() => {
|
||||
if (!cursor) return;
|
||||
|
||||
let animationFrameId: number;
|
||||
let hoveredElement: Element | null = null;
|
||||
|
||||
const handleMouseOver = (e: MouseEvent) => {
|
||||
hoveredElement = e.target as Element;
|
||||
};
|
||||
|
||||
// The mouse move handler is throttled with requestAnimationFrame to ensure
|
||||
// the animation is smooth and doesn't cause performance issues.
|
||||
@@ -31,7 +36,12 @@ export const FancyCursor = memo(() => {
|
||||
// which effectively centers it on the pointer without affecting the visuals.
|
||||
cursor.style.transform = `translate3d(${e.clientX}px, ${e.clientY}px, 0) translate(-50%, -50%)`;
|
||||
|
||||
const el = document.elementFromPoint(e.clientX, e.clientY);
|
||||
// Use the cached hovered element if available, otherwise fallback to elementFromPoint
|
||||
// This fallback is mostly for the initial state before any mouseover events
|
||||
if (!hoveredElement) {
|
||||
hoveredElement = document.elementFromPoint(e.clientX, e.clientY);
|
||||
}
|
||||
const el = hoveredElement;
|
||||
const classList = cursor.classList;
|
||||
|
||||
// Coercing to boolean with `!!` is a micro-optimization.
|
||||
@@ -49,11 +59,13 @@ export const FancyCursor = memo(() => {
|
||||
|
||||
// Using a passive event listener can improve scrolling performance.
|
||||
window.addEventListener('mousemove', handleMouseMove, { passive: true });
|
||||
window.addEventListener('mouseover', handleMouseOver, { passive: true });
|
||||
|
||||
// The cleanup function removes the event listener when the component unmounts
|
||||
// to prevent memory leaks.
|
||||
return () => {
|
||||
window.removeEventListener('mousemove', handleMouseMove);
|
||||
window.removeEventListener('mouseover', handleMouseOver);
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
};
|
||||
}, []); // The empty dependency array ensures this effect runs only once.
|
||||
|
||||
Reference in New Issue
Block a user