typescriptintermediate
Drag & Drop Sortable List
Reorder list items with native HTML drag and drop events — no external library required.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useRef } from 'react';
export function useSortable<T>(initial: T[]) {
const [items, setItems] = useState(initial);
const dragIdx = useRef<number | null>(null);
const onDragStart = (index: number) => {
dragIdx.current = index;
};
const onDragOver = (e: React.DragEvent, index: number) => {
e.preventDefault();
if (dragIdx.current === null || dragIdx.current === index) return;
setItems((prev) => {
const next = [...prev];
const [moved] = next.splice(dragIdx.current!, 1);
next.splice(index, 0, moved);
dragIdx.current = index;
return next;
});
};
const onDragEnd = () => {
dragIdx.current = null;
};
return { items, onDragStart, onDragOver, onDragEnd };
}Use Cases
- Task board reordering
- Playlist management
- Priority lists
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Virtualized List Component
Render large lists efficiently by only rendering visible items with calculated scroll positioning.
Best for: Rendering 10k+ item lists
#virtualization#performance
typescriptbeginner
useHover Hook
Tracks whether an element is being hovered using mouse enter/leave events with a ref.
Best for: Tooltip triggers
#hooks#mouse
typescriptadvanced
Optimistic List with Rollback
A list component that immediately reflects mutations and rolls back on server error.
Best for: Todo lists
#optimistic-ui#list
typescriptbeginner
useClipboard Hook (Advanced)
Clipboard hook with read, write, and auto-reset of the copied state after a timeout.
Best for: Copy-to-clipboard buttons
#hooks#clipboard