kipluo
React6 min read1 steps

Magnetic Button in React (Headless Hook Pattern)

Calling getBoundingClientRect() on every pointermove works for one button, but on a dense grid of cards or toolbar buttons it can trigger unnecessary layout reads. Here is a headless ref-pair hook that caches geometry cleanly.

You needReact 18+Performance profiling basics
Loading demo
Caching the bounding box on pointerenter eliminates per-frame layout reads during fast cursor sweeps.Component page

1. Cache getBoundingClientRect() on pointerenter

Measure the stationary field element once on pointerenter (and invalidate on window scroll/resize). During pointermove, perform pure arithmetic on the cached DOMRect—zero layout queries at 120 Hz.

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

export function useHeadlessMagnetic<Field extends HTMLElement, Target extends HTMLElement>({
  strength = 0.35,
  max = 18,
} = {}) {
  const fieldRef = useRef<Field>(null);
  const targetRef = useRef<Target>(null);

  useEffect(() => {
    const field = fieldRef.current;
    const target = targetRef.current;
    if (!field || !target) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    let rect: DOMRect | null = null;
    let x = 0, y = 0, vx = 0, vy = 0, tx = 0, ty = 0, raf = 0, last = 0;

    const tick = (now: number) => {
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;
      vx += (-280 * (x - tx) - 20 * vx) * dt;
      vy += (-280 * (y - ty) - 20 * vy) * dt;
      x += vx * dt;
      y += vy * dt;
      target.style.transform = `translate3d(${x.toFixed(2)}px, ${y.toFixed(2)}px, 0)`;

      if (Math.abs(vx) > 0.05 || Math.abs(vy) > 0.05 || Math.abs(x - tx) > 0.05 || Math.abs(y - ty) > 0.05) {
        raf = requestAnimationFrame(tick);
      } else {
        target.style.transform = `translate3d(${tx}px, ${ty}px, 0)`;
        raf = 0;
      }
    };

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

    const onEnter = () => { rect = field.getBoundingClientRect(); };
    const invalidate = () => { rect = null; };
    const onMove = (e: PointerEvent) => {
      if (e.pointerType === "touch") return;
      const r = rect ?? (rect = field.getBoundingClientRect());
      tx = Math.max(-max, Math.min(max, (e.clientX - (r.left + r.width / 2)) * strength));
      ty = Math.max(-max, Math.min(max, (e.clientY - (r.top + r.height / 2)) * strength));
      wake();
    };
    const onLeave = () => { rect = null; tx = 0; ty = 0; wake(); };

    field.addEventListener("pointerenter", onEnter);
    field.addEventListener("pointermove", onMove);
    field.addEventListener("pointerleave", onLeave);
    window.addEventListener("scroll", invalidate, { passive: true });
    window.addEventListener("resize", invalidate, { passive: true });
    return () => {
      cancelAnimationFrame(raf);
      field.removeEventListener("pointerenter", onEnter);
      field.removeEventListener("pointermove", onMove);
      field.removeEventListener("pointerleave", onLeave);
      window.removeEventListener("scroll", invalidate);
      window.removeEventListener("resize", invalidate);
    };
  }, [strength, max]);

  return { fieldRef, targetRef };
}

Accessibility checklist

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

0 of 2 checked

Build it yourself or install it

Build it yourself when

You are building a custom headless hook layer for an internal design system.

Install Kipluo when

Kipluo handles the ref separation, fixed-step Euler spring scheduling, and theme styling automatically.

Keep building