kipluo
React7 min read3 steps

How to Build a Magnetic Button in React

Learn how to measure pointer offset from an element's center, clamp displacement cleanly, integrate velocity with a 120 Hz spring loop, and guard against touch and reduced-motion pitfalls.

You needReact 18+Basic Pointer EventsTailwind CSS or plain CSS transforms
Loading demo
Move your cursor near the button to feel the spring-bounded attraction, then leave quickly to test overshoot.Component page

1. Why CSS transitions feel stiff on magnetic hover

The naive way to build a magnetic button is calling setState({ x, y }) inside onMouseMove with a CSS transition: transform 150ms ease-out. On paper it works, but in practice two problems show up immediately: React re-renders on every mouse pixel, and CSS transitions reset their easing curve on every update instead of preserving velocity.

Instead, mutate element.style.transform directly inside a requestAnimationFrame loop driven by a 2D spring. React never re-renders during mouse movement, and when the cursor exits fast, the button carries real momentum back to (0, 0).

2. Compute pointer offset relative to the button center

Track pointer coordinates relative to the wrapper's center, multiply by a strength factor (around 0.25–0.4), and clamp to a maximum pixel radius so the button never runs away from the user's click target.

Always ignore touch pointers (e.pointerType === 'touch')—magnetic drift on touch makes taps feel like the UI is dodging the user's finger.

useMagneticSpring.ts
import { useEffect, useRef } from "react";

type Options = { strength?: number; maxOffset?: number; stiffness?: number; damping?: number };

export function useMagneticSpring<T extends HTMLElement>({
  strength = 0.35,
  maxOffset = 22,
  stiffness = 260,
  damping = 18,
}: Options = {}) {
  const ref = useRef<T>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    let x = 0, y = 0, vx = 0, vy = 0, tx = 0, ty = 0;
    let raf = 0;
    let last = 0;

    const tick = (now: number) => {
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;

      const fx = -stiffness * (x - tx) - damping * vx;
      const fy = -stiffness * (y - ty) - damping * vy;
      vx += fx * dt;
      vy += fy * dt;
      x += vx * dt;
      y += vy * dt;

      el.style.transform = `translate3d(${x.toFixed(2)}px, ${y.toFixed(2)}px, 0)`;

      const moving =
        Math.abs(vx) > 0.05 || Math.abs(vy) > 0.05 ||
        Math.abs(x - tx) > 0.05 || Math.abs(y - ty) > 0.05;

      if (moving) {
        raf = requestAnimationFrame(tick);
      } else {
        x = tx; y = ty; vx = 0; vy = 0;
        el.style.transform = `translate3d(${x}px, ${y}px, 0)`;
        raf = 0;
      }
    };

    const wake = () => {
      if (!raf) {
        last = performance.now();
        raf = requestAnimationFrame(tick);
      }
    };

    const onMove = (e: PointerEvent) => {
      if (e.pointerType === "touch") return;
      const r = el.getBoundingClientRect();
      const dx = (e.clientX - (r.left + r.width / 2)) * strength;
      const dy = (e.clientY - (r.top + r.height / 2)) * strength;
      tx = Math.max(-maxOffset, Math.min(maxOffset, dx));
      ty = Math.max(-maxOffset, Math.min(maxOffset, dy));
      wake();
    };

    const onLeave = () => {
      tx = 0;
      ty = 0;
      wake();
    };

    el.addEventListener("pointermove", onMove);
    el.addEventListener("pointerleave", onLeave);
    return () => {
      cancelAnimationFrame(raf);
      el.removeEventListener("pointermove", onMove);
      el.removeEventListener("pointerleave", onLeave);
    };
  }, [strength, maxOffset, stiffness, damping]);

  return ref;
}

3. Avoid the classic edge-jitter bug with a static hit wrapper

If you attach pointermove directly to the element that is translating, moving the button shifts its own getBoundingClientRect()—which changes the pointer's offset from center on the very next frame and creates a feedback oscillation near the border.

Fix this by attaching the pointer listener to a stationary outer wrapper while translating only the inner button element.

MagneticButton.tsx
import { useMagneticSpring } from "./useMagneticSpring";

export function MagneticButton({ children }: { children: React.ReactNode }) {
  const innerRef = useMagneticSpring<HTMLButtonElement>({ strength: 0.35, maxOffset: 18 });

  return (
    <span className="inline-block p-3">
      <button
        ref={innerRef}
        type="button"
        className="rounded-full bg-zinc-900 px-6 py-3 text-sm font-semibold text-white will-change-transform focus-visible:outline-2 focus-visible:outline-offset-2"
      >
        {children}
      </button>
    </span>
  );
}

Accessibility checklist

Tick each one off as you check your build. Your ticks stay in this browser.

0 of 3 checked

Build it yourself or install it

Build it yourself when

You only need one hero CTA button and want zero extra abstractions beyond ~60 lines of TypeScript.

Install Kipluo when

You want stationary outer hit-field detection, fixed-timestep 120 Hz springs, optional Web Audio cues, and Flutter parity out of the box.

Keep building