useCopyToClipboard Hook
Copy text to clipboard with success state and automatic reset timer using the Clipboard API.
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.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
useClickOutside — Outside Click Detection
Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.