Utils
use-drag
Pointer-based drag hook with pointer capture, drag info callbacks and an isDragging flag
Installation
$npx litefy@latest add use-drag
$pnpm dlx litefy@latest add use-drag
$yarn dlx litefy@latest add use-drag
$bun --bun litefy@latest add use-drag
Usage
Bind handlePointerDown to the drag handle. The hook captures the pointer, tracks movement on the document and reports deltas through callbacks.
Drag mePointer down to drag
"use client";import * as React from "react";import { useDrag } from "@/ui";export default function UseDragBasicDemo() { const [offset, setOffset] = React.useState({ x: 0, y: 0 }); const startRef = React.useRef({ x: 0, y: 0 }); const drag = useDrag({ onDragStart: () => { startRef.current = offset; }, onDragMove: ({ dx, dy }) => { setOffset({ x: startRef.current.x + dx, y: startRef.current.y + dy }); }, }); return ( <div className="flex h-64 items-center justify-center rounded-lg border bg-muted/30 overflow-hidden"> <div onPointerDown={drag.handlePointerDown} style={{ transform: `translate(${offset.x}px, ${offset.y}px)` }} className={ "flex cursor-grab select-none touch-none flex-col items-center justify-center rounded-lg border bg-background px-6 py-4 shadow-md active:cursor-grabbing" + (drag.isDragging ? " ring-2 ring-primary" : "") } > <span className="text-sm font-medium">Drag me</span> <span className="mt-1 text-xs text-muted-foreground"> {drag.isDragging ? "Dragging…" : "Pointer down to drag"} </span> </div> </div> );}API Reference
useDrag
function useDrag(opts?: UseDragOptions): DragResultUseDragOptions
| Property | Type | Default | Description |
|---|---|---|---|
disabled | boolean | false | Ignore pointer down events when true |
onDragStart | (e: React.PointerEvent<HTMLElement>) => void | - | Called when the drag gesture starts |
onDragMove | (info: DragInfo) => void | - | Called on every pointer move while dragging |
onDragEnd | (info: DragInfo) => void | - | Called when the pointer is released |
DragInfo
| Property | Type | Description |
|---|---|---|
dx | number | Horizontal offset from the drag start position |
dy | number | Vertical offset from the drag start position |
clientX | number | Current pointer client X |
clientY | number | Current pointer client Y |
DragResult
| Property | Type | Description |
|---|---|---|
isDragging | boolean | Whether a drag gesture is currently active |
handlePointerDown | (e: React.PointerEvent<HTMLElement>) => void | Bind to the drag handle's onPointerDown |
Notes:
- Deltas are relative to the pointer's start position; callers decide how to accumulate them.
- Uses pointer capture, so the drag keeps tracking even when the pointer leaves the handle.