DOM

useCopyToClipboard

Copy text to the clipboard, tracking the last copied value.

Demo

Copy, then paste to confirm it worked.

copiedText
null

Usage

use-copy-to-clipboard.tsxtsx
import { useCopyToClipboard } from "hookli";

export function Demo() {
  const [copiedText, copy] = useCopyToClipboard();

  return (
    <button type="button" onClick={() => copy("npm i hookli")}>
      {copiedText ? "Copied!" : "Copy"}
    </button>
  );
}

API

useCopyToClipboard.d.tsts
useCopyToClipboard(): [CopiedValue, CopyFn]

Parameters

This hook takes no parameters.

Returns

NameTypeDescription
[0] copiedTextCopiedValueThe last successfully-copied string, or null before any copy or after a failed one.
[1] copyCopyFnWrites text to the clipboard. Resolves true on success, false when the API is unavailable or the write is rejected.

CopiedValue

NameTypeDescription
valuestring | nullThe tracked copied text, or null.

CopyFn

NameTypeDescription
value(text: string) => Promise<boolean>Copies text and reports whether the write succeeded.

Hook

The implementation, straight from hookli. Copy it, or install the package.

src/hooks/use-copy-to-clipboard/use-copy-to-clipboard.tstsx
import { useCallback, useState } from "react";

type CopiedValue = string | null;
type CopyFn = (text: string) => Promise<boolean>;
type UseCopyToClipboardReturn = [CopiedValue, CopyFn];

export function useCopyToClipboard(): UseCopyToClipboardReturn {
  const [copiedText, setCopiedText] = useState<CopiedValue>(null);

  const copy: CopyFn = useCallback(async (text) => {
    if (typeof navigator === "undefined" || !navigator.clipboard) {
      return false;
    }

    try {
      await navigator.clipboard.writeText(text);
      setCopiedText(text);
      return true;
    } catch {
      setCopiedText(null);
      return false;
    }
  }, []);

  return [copiedText, copy];
}

View source on GitHub

Related hooks