useClipboard Hook
A custom React Hook for clipboard copy/paste functionality with TypeScript support
Code
import { useState, useCallback } from 'react';
type ClipboardResult = {
copied: boolean;
copy: (text: string, options?: ClipboardCopyOptions) => Promise<void>;
clear: () => void;
};
type ClipboardCopyOptions = {
onSuccess?: () => void;
onError?: (error: Error) => void;
timeout?: number;
};
function useClipboard(defaultTimeout = 2000): ClipboardResult {
const [copied, setCopied] = useState(false);
const copy = useCallback(__TOKEN_18__ (
text: string,
options: ClipboardCopyOptions = {}
) => {
const { onSuccess, onError, timeout = defaultTimeout } = options;
try {
await navigator.clipboard.writeText(text);
setCopied(true);
onSuccess?.();
// Reset copied state after timeout
setTimeout(() => setCopied(false), timeout);
} __TOKEN_22__ (error) {
setCopied(false);
onError?.(error as Error);
console.error('Failed to copy to clipboard:', error);
}
}, [defaultTimeout]);
const clear = useCallback(() => {
setCopied(false);
}, []);
return { copied, copy, clear };
}
// Usage example
// const { copied, copy } = useClipboard();
// <button onClick={() => copy('Hello World!', {
// onSuccess: () => console.log('Copied!'),
// onError: (err) => console.error('Copy failed:', err)
// })}>
// {copied ? 'Copied!' : 'Copy Text'}
// </button>