1import { useCallback, useEffect, useRef, useState } from "react";
2
3type CopiedValue = string | null;
4
5type CopyFn = (text: string) => Promise<boolean>;
6
7function useCopyToClipboard(delay = 1500) {
8 const [copiedText, setCopiedText] = useState<CopiedValue>(null);
9 const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
10
11 const copy: CopyFn = useCallback(
12 async (text) => {
13 if (!navigator.clipboard) {
14 console.warn("Clipboard not supported");
15 return false;
16 }
17
18 try {
19 await navigator.clipboard.writeText(text);
20 setCopiedText(text);
21
22 if (timeoutRef.current) clearTimeout(timeoutRef.current);
23
24 timeoutRef.current = setTimeout(() => {
25 setCopiedText(null);
26 }, delay);
27
28 return true;
29 } catch (error) {
30 console.warn("Copy failed", error);
31 setCopiedText(null);
32 return false;
33 }
34 },
35 [delay]
36 );
37
38 useEffect(() => {
39 return () => {
40 if (timeoutRef.current) clearTimeout(timeoutRef.current);
41 };
42 }, []);
43
44 return {
45 copied: !!copiedText,
46 copiedText,
47 copy,
48 };
49}
50
51export default useCopyToClipboard;