How to create a custom clipboard hook

Learn how to create a custom copy to clipboard hook.

In this article, I will be sharing how to create a custom hook to copy text to your clipboard.

Recently I was working on a task that involves interacting with browser native navigator APIs, so I checked out MDN docs and decided to write a custom hook and share.


/*Custom Hook File*/
interface ICopyProps{
    textToCopy: string
}

export const useCopy = () => {
const [copiedText, setCopiedText] = useState('')

  function handleCopyText({ textToCopy }: ICopyProps) {
    navigator.clipboard.writeText(textToCopy).then(() => {
      /** 
      You can use a toast to display a success message here
      */
      setCopiedText(textToCopy)
      alert("text copied successfully")

    }, () => {
      /** 
     You can use a toast to display a failed message here
     */
      alert("failed to copy text")
    })
  }

  return { handleCopyText,copiedText }
}    

/* App File 
Import the Custom Hook inside the app file or the file that want to consume it.
*/
import {useCopy} from "./useCopy"
const App = ()=>{
  const { handleCopyText, copiedText} = useCopy()
   return(
    <div>
        <button 
        onClick={()=>handleCopyText({textToCopy:"Helloworld"})}>
        Hello world
        </button>
    </div>
    )
}

The code above shows how to write a custom hook that copies text to a clipboard and saves the copied text to a local state hook.

For beginners, all custom hook names must start with "use", to read more about hooks you can check the react DOCS.

Thanks for taking the time to read this article and I hope you learned something, I will be sharing react tips and code snippets so keep watching this space.