typescriptbeginner

useCopyToClipboard Hook

Copy text to clipboard with success state and automatic reset timer using the Clipboard API.

typescript
import { useState, useCallback } from 'react';

export function useCopyToClipboard(resetMs = 2000) {
  const [copied, setCopied] = useState(false);

  const copy = useCallback(
    async (text: string) => {
      try {
        await navigator.clipboard.writeText(text);
        setCopied(true);
        setTimeout(() => setCopied(false), resetMs);
        return true;
      } catch {
        setCopied(false);
        return false;
      }
    },
    [resetMs]
  );

  return { copied, copy };
}

Use Cases

  • Copy code snippets
  • Share links
  • Copy referral codes

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.