DEV Community

Cover image for The Journey of Creating a Custom Hook that Improves User Experience
Karthick (k)
Karthick (k)

Posted on

The Journey of Creating a Custom Hook that Improves User Experience

Write a blog about creating a new project for a custom hook that improves user experience.

What you should learn from this project
This project teaches a very important React idea: how to copy text to the clipboard with one click.

1) Learn the main goal
The app is about improving user experience.

Instead of asking users to:

select text
press Ctrl + C
then paste it somewhere else
you give them a button that does it automatically.

import { useState } from 'react ';

export function useCopyToClipboard() {
  const [copiedText, setCopiedText] = useState('')

  const copyToClipboard = async (text) => {
    if (!text) {
      setCopiedText('')
      return false
    }

    try {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(text)
      } else {
        const textarea = document.createElement('textarea')
        textarea.value = text
        textarea.setAttribute('readonly', '')
        textarea. style.position = 'fixed'
        textarea. style.top = '-9999px'
        textarea. style.left = '-9999px'

        document.body.appendChild(textarea)
        textarea.select()
        document.execCommand('copy')
        document.body.removeChild(textarea)
      }

      setCopiedText(text)
      return true
    } catch (error) {
      console.error('Copy failed:', error)
      setCopiedText('')
      return false
    }
  }

  return [copiedText, copyToClipboard]
}
Enter fullscreen mode Exit fullscreen mode

## Project idea

When users need to copy a value like an API key, token, link, or code, it is better to make the action easy with one click instead of forcing them to type Ctrl + C manually.

This app demonstrates that idea with a fake API key and a Copy button.

Top comments (0)