useCopyToClipboard Hook

A React custom hook that copies text to the clipboard and sets a state to provide user feedback. Useful for buttons that copy code or links.

TypeScript7/17/2025
#react#hooks#clipboard
TypeScript
import { useState } from 'react';

export function useCopyToClipboard() {
  const [isCopied, setIsCopied] = useState(false);

  const copy = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  return { isCopied, copy };
}
...
Loading comments...