typescriptbeginner
useClipboard Hook (Advanced)
Clipboard hook with read, write, and auto-reset of the copied state after a timeout.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useCallback, useRef } from 'react';
export function useClipboard(resetDelay = 2000) {
const [copied, setCopied] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout>>();
const copy = useCallback(async (text: string) => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => setCopied(false), resetDelay);
return true;
} catch {
setCopied(false);
return false;
}
}, [resetDelay]);
const read = useCallback(async () => {
try {
return await navigator.clipboard.readText();
} catch {
return null;
}
}, []);
return { copy, read, copied };
}Use Cases
- Copy-to-clipboard buttons
- Sharing URLs
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
useCopyToClipboard Hook
Copy text to clipboard with success state and automatic reset timer using the Clipboard API.
Best for: Copy code snippets
#hooks#clipboard
typescriptbeginner
useHover Hook
Tracks whether an element is being hovered using mouse enter/leave events with a ref.
Best for: Tooltip triggers
#hooks#mouse
typescriptintermediate
useLongPress Hook
Detects long press gestures on touch and mouse devices with configurable threshold.
Best for: Context menus
#hooks#gesture
typescriptbeginner
useClickAway Hook
Fires a callback when a click is detected outside the referenced element.
Best for: Dropdown close on outside click
#hooks#click-outside