Skip to content

UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.

perf(registry): improve MagicCard performance with useCallback and extend interface for enhanced flexibility (#234)

Julian S.50f9fe6d6414
diff --git a/registry/components/magicui/magic-card.tsx b/registry/components/magicui/magic-card.tsx
index 80d9a061..4177af64 100644
--- a/registry/components/magicui/magic-card.tsx
+++ b/registry/components/magicui/magic-card.tsx
@@ -1,13 +1,11 @@
"use client";
-import React from "react";
+import React, { useCallback, useEffect } from "react";
import { motion, useMotionTemplate, useMotionValue } from "framer-motion";
import { cn } from "@/lib/utils";
-export interface MagicCardProps {
- children: React.ReactNode;
- className?: string;
+export interface MagicCardProps extends React.HTMLAttributes<HTMLDivElement> {
gradientSize?: number;
gradientColor?: string;
gradientOpacity?: number;
@@ -15,21 +13,37 @@ export interface MagicCardProps {
export function MagicCard({
children,
- className = "",
+ className,
gradientSize = 200,
gradientColor = "#262626",
+ gradientOpacity = 0.8,
}: MagicCardProps) {
- const mouseX = useMotionValue(0);
- const mouseY = useMotionValue(0);
+ const mouseX = useMotionValue(-gradientSize);
+ const mouseY = useMotionValue(-gradientSize);
+
+ const handleMouseMove = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ const { left, top } = e.currentTarget.getBoundingClientRect();
+ mouseX.set(e.clientX - left);
+ mouseY.set(e.clientY - top);
+ },
+ [mouseX, mouseY],
+ );
+
+ const handleMouseLeave = useCallback(() => {
+ mouseX.set(-gradientSize);
+ mouseY.set(-gradientSize);
+ }, [mouseX, mouseY, gradientSize]);
+
+ useEffect(() => {
+ mouseX.set(-gradientSize);
+ mouseY.set(-gradientSize);
+ }, [mouseX, mouseY, gradientSize]);
return (
<div
- onMouseMove={(e) => {
- const { left, top } = e.currentTarget.getBoundingClientRect();
-
- mouseX.set(e.clientX - left);
- mouseY.set(e.clientY - top);
- }}
+ onMouseMove={handleMouseMove}
+ onMouseLeave={handleMouseLeave}
className={cn(
"group relative flex size-full overflow-hidden rounded-xl bg-neutral-100 dark:bg-neutral-900 border text-black dark:text-white",
className,
@@ -37,11 +51,12 @@ export function MagicCard({
>
<div className="relative z-10">{children}</div>
<motion.div
- className="pointer-events-none absolute -inset-px rounded-xl opacity-0 transition duration-300 group-hover:opacity-100"
+ className="pointer-events-none absolute -inset-px rounded-xl opacity-0 transition-opacity duration-300 group-hover:opacity-100"
style={{
background: useMotionTemplate`
- radial-gradient(${gradientSize}px circle at ${mouseX}px ${mouseY}px, ${gradientColor}, transparent 100%)
- `,
+ radial-gradient(${gradientSize}px circle at ${mouseX}px ${mouseY}px, ${gradientColor}, transparent 100%)
+ `,
+ opacity: gradientOpacity,
}}
/>
</div>