typescriptbeginner
useCopyToClipboard Hook
Copy text to clipboard with success state and automatic reset timer using the Clipboard API.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useCallback } from 'react';
export function useCopyToClipboard(resetMs = 2000) {
const [copied, setCopied] = useState(false);
const copy = useCallback(
async (text: string) => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), resetMs);
return true;
} catch {
setCopied(false);
return false;
}
},
[resetMs]
);
return { copied, copy };
}Use Cases
- Copy code snippets
- Share links
- Copy referral codes
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage