21 lines · 582 B
import { useEffect, useState } from "react";

const RESET_MS = 1600;

/** Copies text to the clipboard and reports `copied` briefly afterwards. */
export function useCopy(): { copied: boolean; copy: (text: string) => Promise<void> } {
  const [copied, setCopied] = useState(false);
  useEffect(() => {
    if (!copied) return;
    const timer = setTimeout(() => setCopied(false), RESET_MS);
    return () => clearTimeout(timer);
  }, [copied]);
  return {
    copied,
    copy: async (text) => {
      await navigator.clipboard.writeText(text);
      setCopied(true);
    },
  };
}