Skip to content

Instantly share code, notes, and snippets.

@adyontech
Created February 12, 2020 16:40
Show Gist options
  • Save adyontech/cee67e8972a585337d4661daa8b9250c to your computer and use it in GitHub Desktop.
Save adyontech/cee67e8972a585337d4661daa8b9250c to your computer and use it in GitHub Desktop.
react-copy-clipboard ~ 1 kb
import { useState, useRef, useEffect } from 'react'
import copyToClipboard from 'copy-to-clipboard'

const useClipboard = () => {
  const [hasCopied, setHasCopied] = useState(false)
  const timeoutRef = useRef<NodeJS.Timeout | null>(null)

  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
      }
    }
  }, [])

  const copy = (value: string) => {
    copyToClipboard(value)
    setHasCopied(true)
    timeoutRef.current = setTimeout(() => setHasCopied(false), 1500)
  }

  return {
    onCopy: copy,
    hasCopied,
  }
}

export default useClipboard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment