Custom Cursor
A custom cursor component for React and Tailwind CSS: a dot that sits on the pointer and a ring that trails it on a spring, growing over links and buttons and showing short labels like “View” or “Play”. Scoped to a container or the whole page, and it falls back to the native cursor on touch screens and with reduced motion.
- Spring trailing ring
- Hover labels
- Container or page scope
- Zero re-renders on move
- Touch & reduced-motion fallback
Brand and product design for small software teams.
The ring grows over anything clickable. Plain text keeps the small dot.
import { ArrowUpRight } from "lucide-react";
import { CustomCursor } from "@/components/dusk/custom-cursor/custom-cursor";
export default function CustomCursorDemo() {
return (
<CustomCursor className="flex h-80 w-full max-w-xl flex-col justify-between overflow-hidden rounded-xl border border-white/10 bg-background p-6">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="font-semibold tracking-tight text-foreground">Northwind Studio</span>
<nav aria-label="Demo" className="flex gap-1 text-sm text-white/70">
{["Work", "About", "Contact"].map((item) => (
<button key={item} type="button" className="rounded-md px-2.5 py-1 hover:text-white">
{item}
</button>
))}
</nav>
</div>
<div>
<h3 className="max-w-sm text-2xl font-semibold tracking-tight text-foreground">
Brand and product design for small software teams.
</h3>
</div>
<div className="flex items-end justify-between gap-4">
<p className="max-w-[16rem] text-sm text-muted-foreground">
The ring grows over anything clickable. Plain text keeps the small dot.
</p>
<button
type="button"
data-cursor-label="Open"
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
>
View case <ArrowUpRight className="size-4" aria-hidden />
</button>
</div>
</CustomCursor>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/custom-cursor.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/custom-cursor/custom-cursor.tsx.custom-cursor.tsx "use client"; import * as React from "react"; import { createPortal } from "react-dom"; import { AnimatePresence, motion, useMotionValue, useReducedMotion, useSpring, type SpringOptions, } from "motion/react"; import { cn } from "@/lib/utils"; const HOVER_SELECTOR = 'a[href], button:not(:disabled), [role="button"], [role="link"], label[for], summary, select, [data-cursor="hover"], [data-cursor-label]'; const NATIVE_SELECTOR = 'input:not([type="button"]):not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="range"]), textarea, [contenteditable=""], [contenteditable="true"], [data-cursor="native"]'; // The native cursor is hidden only where the custom one is drawn; text fields keep their caret. const CURSOR_CSS = ` [data-dusk-cursor="on"], [data-dusk-cursor="on"] * { cursor: none !important; } [data-dusk-cursor="on"] :is(${NATIVE_SELECTOR}), [data-dusk-cursor="on"] :is(${NATIVE_SELECTOR}) * { cursor: auto !important; } `; export interface CustomCursorProps extends React.ComponentProps<"div"> { /** * `container` draws the cursor only inside this element (which wraps `children`). * `page` draws it over the whole document; render it once, anywhere. */ scope?: "container" | "page"; /** Diameter of the trailing ring in px. */ ringSize?: number; /** Ring diameter over links, buttons and `[data-cursor="hover"]`. */ hoverSize?: number; /** Ring diameter when the hovered element has a `data-cursor-label`. */ labelSize?: number; /** Diameter of the dot in px. */ dotSize?: number; /** Spring for the ring. The dot uses a much stiffer one so it stays under the pointer. */ spring?: SpringOptions; /** Extra selector for elements that should enlarge the ring. Links and buttons are always included. */ hoverSelector?: string; } type CursorState = { visible: boolean; mode: "idle" | "hover" | "native"; label: string | null; pressed: boolean; }; const IDLE: CursorState = { visible: false, mode: "idle", label: null, pressed: false }; function sameState(a: CursorState, b: CursorState) { return a.visible === b.visible && a.mode === b.mode && a.label === b.label && a.pressed === b.pressed; } /** True only on the client, for a fine pointer (mouse / trackpad). `false` during SSR and hydration. */ function useFinePointer() { return React.useSyncExternalStore( (onChange) => { const query = window.matchMedia("(hover: hover) and (pointer: fine)"); query.addEventListener("change", onChange); return () => query.removeEventListener("change", onChange); }, () => window.matchMedia("(hover: hover) and (pointer: fine)").matches, () => false ); } /** * A smooth trailing cursor: a dot that sits on the pointer and a ring that * follows on a spring. The ring grows over links, buttons and anything with * `data-cursor="hover"`, and shows the text of `data-cursor-label` inside it. * Over text fields (or `data-cursor="native"`) it steps aside for the caret. * * Scoped to its own container by default, so the native cursor is hidden only * there. Pointer positions are motion values, so moving never re-renders React. * Touch devices, coarse pointers and reduced motion keep the native cursor and * render nothing extra. The drawn layers are `aria-hidden` and never take * pointer events. */ export function CustomCursor({ scope = "container", ringSize = 32, hoverSize = 56, labelSize = 76, dotSize = 6, spring = { stiffness: 380, damping: 32, mass: 0.6 }, hoverSelector, className, children, onPointerMove, onPointerEnter, onPointerLeave, onPointerDown, onPointerUp, ...props }: CustomCursorProps) { const reduceMotion = useReducedMotion(); const finePointer = useFinePointer(); const enabled = finePointer && !reduceMotion; const rootRef = React.useRef<HTMLDivElement>(null); const [state, setState] = React.useState<CursorState>(IDLE); const update = React.useCallback((patch: Partial<CursorState>) => { setState((prev) => { const next = { ...prev, ...patch }; return sameState(prev, next) ? prev : next; }); }, []); const x = useMotionValue(0); const y = useMotionValue(0); const ringX = useSpring(x, spring); const ringY = useSpring(y, spring); const dotX = useSpring(x, { stiffness: 1400, damping: 60, mass: 0.2 }); const dotY = useSpring(y, { stiffness: 1400, damping: 60, mass: 0.2 }); const last = React.useRef({ clientX: 0, clientY: 0, seen: false }); const selector = hoverSelector ? `${HOVER_SELECTOR}, ${hoverSelector}` : HOVER_SELECTOR; /** Places the cursor and works out what it is over. Shared by both scopes. */ const track = React.useCallback( (clientX: number, clientY: number, target: EventTarget | null) => { const root = rootRef.current; let px = clientX; let py = clientY; if (scope === "container" && root) { const rect = root.getBoundingClientRect(); px = clientX - rect.left + root.scrollLeft; py = clientY - rect.top + root.scrollTop; } const firstMove = !last.current.seen; last.current = { clientX, clientY, seen: true }; if (firstMove) { // Appear under the pointer instead of flying in from the corner. x.jump(px); y.jump(py); ringX.jump(px); ringY.jump(py); dotX.jump(px); dotY.jump(py); } else { x.set(px); y.set(py); } const el = target instanceof Element ? target : null; const limit = scope === "container" ? root : document.documentElement; const inside = (node: Element | null) => (node && limit?.contains(node) ? node : null); if (inside(el?.closest(NATIVE_SELECTOR) ?? null)) { update({ visible: true, mode: "native", label: null }); return; } const hit = inside(el?.closest(selector) ?? null); const label = hit?.closest("[data-cursor-label]")?.getAttribute("data-cursor-label") || null; update({ visible: true, mode: hit ? "hover" : "idle", label }); }, [scope, selector, update, x, y, ringX, ringY, dotX, dotY] ); const hideCursor = React.useCallback(() => { last.current.seen = false; update({ visible: false, pressed: false }); }, [update]); // Mark the scope so the injected stylesheet hides the native cursor there only. React.useEffect(() => { if (!enabled) return; const target = scope === "page" ? document.documentElement : rootRef.current; if (!target) return; target.setAttribute("data-dusk-cursor", "on"); return () => target.removeAttribute("data-dusk-cursor"); }, [enabled, scope]); // Page scope: follow the pointer on the window. React.useEffect(() => { if (!enabled || scope !== "page") return; const move = (event: PointerEvent) => { if (event.pointerType !== "mouse") return; track(event.clientX, event.clientY, event.target); }; const down = (event: PointerEvent) => event.pointerType === "mouse" && update({ pressed: true }); const up = () => update({ pressed: false }); const leave = () => hideCursor(); window.addEventListener("pointermove", move, { passive: true }); window.addEventListener("pointerdown", down, { passive: true }); window.addEventListener("pointerup", up, { passive: true }); document.documentElement.addEventListener("pointerleave", leave); window.addEventListener("blur", leave); return () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerdown", down); window.removeEventListener("pointerup", up); document.documentElement.removeEventListener("pointerleave", leave); window.removeEventListener("blur", leave); }; }, [enabled, scope, track, update, hideCursor]); // Container scope: keep the cursor glued to the pointer while the page scrolls under it. React.useEffect(() => { if (!enabled || scope !== "container" || !state.visible) return; const onScroll = () => { const { clientX, clientY, seen } = last.current; if (!seen) return; track(clientX, clientY, document.elementFromPoint(clientX, clientY)); }; window.addEventListener("scroll", onScroll, { passive: true, capture: true }); return () => window.removeEventListener("scroll", onScroll, { capture: true }); }, [enabled, scope, state.visible, track]); const fixed = scope === "page"; const size = state.mode === "hover" ? (state.label ? labelSize : hoverSize) : ringSize; const showLayers = state.visible && state.mode !== "native"; const layers = enabled ? ( <div aria-hidden data-slot="custom-cursor" // Container scope: no clipping here, so the ring can follow into scrolled content; the container clips. className={cn("pointer-events-none inset-0 z-[9999]", fixed ? "fixed overflow-hidden" : "absolute")} > <style href="dusk-custom-cursor" precedence="default"> {CURSOR_CSS} </style> <motion.div className="absolute left-0 top-0" style={{ x: ringX, y: ringY }}> <motion.div className="absolute grid place-items-center rounded-full border border-white/40" initial={false} animate={{ width: size, height: size, x: -size / 2, y: -size / 2, opacity: showLayers ? 1 : 0, scale: state.pressed ? 0.9 : 1, }} transition={{ type: "spring", stiffness: 420, damping: 30, mass: 0.5, opacity: { duration: 0.18 } }} > <motion.span className="absolute inset-0 rounded-full bg-white" initial={false} animate={{ opacity: state.label ? 1 : state.mode === "hover" ? 0.06 : 0 }} transition={{ duration: 0.2 }} /> <AnimatePresence> {state.label && showLayers && ( <motion.span key={state.label} className="relative px-2 text-center text-xs font-medium leading-tight text-black" initial={{ opacity: 0, scale: 0.96 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.96 }} transition={{ duration: 0.18 }} > {state.label} </motion.span> )} </AnimatePresence> </motion.div> </motion.div> <motion.div className="absolute left-0 top-0" style={{ x: dotX, y: dotY }}> <motion.div className="absolute rounded-full bg-white" style={{ width: dotSize, height: dotSize, left: -dotSize / 2, top: -dotSize / 2 }} initial={false} animate={{ opacity: showLayers && state.mode === "idle" ? 1 : 0, scale: showLayers && state.mode === "idle" ? 1 : 0.2 }} transition={{ duration: 0.15 }} /> </motion.div> </div> ) : null; if (scope === "page") { return ( <> {children} {layers && createPortal(layers, document.body)} </> ); } return ( <div ref={rootRef} data-slot="custom-cursor-area" className={cn("relative", className)} onPointerEnter={(event) => { onPointerEnter?.(event); if (enabled && event.pointerType === "mouse") track(event.clientX, event.clientY, event.target); }} onPointerMove={(event) => { onPointerMove?.(event); if (enabled && event.pointerType === "mouse") track(event.clientX, event.clientY, event.target); }} onPointerLeave={(event) => { onPointerLeave?.(event); if (enabled) hideCursor(); }} onPointerDown={(event) => { onPointerDown?.(event); if (enabled && event.pointerType === "mouse") update({ pressed: true }); }} onPointerUp={(event) => { onPointerUp?.(event); if (enabled) update({ pressed: false }); }} {...props} > {children} {layers} </div> ); }
Usage
import { CustomCursor } from "@/components/dusk/custom-cursor/custom-cursor"
export function Showcase() {
return (
<CustomCursor className="grid gap-4 overflow-hidden rounded-xl p-6 sm:grid-cols-3">
<a href="/work/aurora" data-cursor-label="View">Aurora</a>
<a href="/work/tide" data-cursor-label="View">Tide</a>
<div data-cursor="hover">Anything can enlarge the ring</div>
</CustomCursor>
)
}Examples
Hover labels
Add data-cursor-label to any element and the ring fills in and shows the text. Keep labels to a word or two; size the bubble with labelSize.
import { CustomCursor } from "@/components/dusk/custom-cursor/custom-cursor";
const tiles = [
{ title: "Night drive", label: "Play", tone: "bg-zinc-800" },
{ title: "Field notes", label: "Read", tone: "bg-stone-800" },
{ title: "Lowlight", label: "View", tone: "bg-neutral-800" },
];
export default function CustomCursorLabels() {
return (
<CustomCursor
labelSize={84}
className="grid w-full max-w-2xl gap-3 overflow-hidden rounded-xl p-1 sm:grid-cols-3"
>
{tiles.map((tile) => (
<button
key={tile.title}
type="button"
data-cursor-label={tile.label}
className={`flex h-48 flex-col justify-end rounded-xl border ${tile.tone} p-4 text-left outline-none ring-white/60 focus-visible:ring-2`}
>
<span className="text-sm font-medium text-white">{tile.title}</span>
<span className="text-xs text-white/70">{tile.label} →</span>
</button>
))}
</CustomCursor>
);
}Spring feel
spring sets how the ring follows: stiff and damped for a snappy cursor, soft and heavy for a floaty one. data-cursor="hover" enlarges the ring over non-interactive elements too.
Snappy
stiffness 900 · damping 50Floaty
stiffness 120 · damping 18import { CustomCursor } from "@/components/dusk/custom-cursor/custom-cursor";
const presets = [
{ name: "Snappy", spring: { stiffness: 900, damping: 50, mass: 0.3 }, ringSize: 24 },
{ name: "Floaty", spring: { stiffness: 120, damping: 18, mass: 0.9 }, ringSize: 44 },
];
export default function CustomCursorSprings() {
return (
<div className="grid w-full max-w-2xl gap-3 sm:grid-cols-2">
{presets.map((preset) => (
<CustomCursor
key={preset.name}
spring={preset.spring}
ringSize={preset.ringSize}
className="flex h-56 flex-col items-center justify-center gap-4 overflow-hidden rounded-xl border border-white/10 bg-background"
>
<p className="text-lg font-semibold text-white">{preset.name}</p>
<code className="font-mono text-[11px] text-white/55">
stiffness {preset.spring.stiffness} · damping {preset.spring.damping}
</code>
<button
type="button"
data-cursor="hover"
className="rounded-md border border-white/15 px-3 py-1.5 text-xs text-white/80"
>
Hover me
</button>
</CustomCursor>
))}
</div>
);
}Page scope
Render <CustomCursor scope="page" /> once (for example in a layout) to draw the cursor across the whole document. It is portaled to body; text fields and data-cursor="native" keep the native cursor.
With scope="page" the cursor follows you across the whole document. Text fields keep their native caret.
"use client";
import * as React from "react";
import { CustomCursor } from "@/components/dusk/custom-cursor/custom-cursor";
import { Switch } from "@/components/ui/switch";
export default function CustomCursorPage() {
const [on, setOn] = React.useState(false);
return (
<div className="flex flex-col items-center gap-3 text-center">
<label className="flex items-center gap-3 text-sm text-white/80">
<Switch checked={on} onCheckedChange={setOn} />
Page-wide cursor
</label>
<p className="max-w-xs text-xs text-white/55">
With <code className="font-mono text-white/70">scope="page"</code> the cursor follows you across the
whole document. Text fields keep their native caret.
</p>
<input
type="text"
placeholder="Try typing here"
className="h-9 w-56 rounded-md border border-white/15 bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"
/>
{on && <CustomCursor scope="page" />}
</div>
);
}API Reference
In container scope it renders a div that accepts any HTML attribute. Data attributes on descendants: data-cursor="hover", data-cursor-label="…", data-cursor="native".
| Prop | Type | Default | Description |
|---|---|---|---|
| scope | "container" | "page" | "container" | Draw only inside this element (wrapping children), or across the whole page. |
| ringSize | number | 32 | Ring diameter in px. |
| hoverSize | number | 56 | Ring diameter over links, buttons and [data-cursor="hover"]. |
| labelSize | number | 76 | Ring diameter when showing a data-cursor-label. |
| dotSize | number | 6 | Dot diameter in px. |
| spring | SpringOptions | { stiffness: 380, damping: 32, mass: 0.6 } | Spring for the trailing ring. The dot uses a much stiffer one. |
| hoverSelector | string | — | Extra CSS selector for elements that enlarge the ring. |
| className | string | — | Classes for the container (container scope only). |
Accessibility
- The drawn dot and ring are aria-hidden and pointer-events: none; clicks, focus and hover states of your content are untouched.
- The native cursor is hidden only inside the scoped area, and only once the custom cursor is active; text inputs keep their caret.
- Touch screens, pens and coarse pointers keep the native cursor and render nothing extra.
- With prefers-reduced-motion the component is disabled entirely and the native cursor stays.
- Pointer tracking uses motion values, so moving the mouse never re-renders React.