1 "use client"
2
3 import { useCallback, useEffect, useRef, useState } from "react"
4
5 type useCopyReturnType = {
6 isCopied: boolean
7 handleCopy: () => void
8 }
9
10 export const useCopy = (text: string): useCopyReturnType => {
11 const [isCopied, setIsCopied] = useState(false)
12 const copyTimeout = useRef<number>(0)
13
14 const handleCopy = useCallback(() => {
15 navigator.clipboard
16 .writeText(text.trim())
17 .then(() => {
18 setIsCopied(true)
19 copyTimeout.current = window.setTimeout(() => {
20 setIsCopied(false)
21 }, 1000)
22 })
23 .catch(console.error)
24 }, [text])
25
26 useEffect(() => () => window.clearTimeout(copyTimeout.current), [])
27
28 return { isCopied, handleCopy }
29 }