useCopyToClipboard
Copy text to the clipboard and track whether a copy just succeeded.
API
function useCopyToClipboard(
resetTimeout?: number,
): [copied: boolean, copy: (text: string) => Promise<boolean>];
Parameters:
resetTimeout: The time (milliseconds)copiedstaystrueafter a successful copy. Default is1000.
Results:
copied: Whether a copy succeeded within the lastresetTimeoutmilliseconds.copy: Copytextto the clipboard and return aPromisethat resolves with whether it succeeded.
Notes
- The async Clipboard API requires a secure context (
httpsorlocalhost). Outside of it, the hook falls back todocument.execCommand("copy"), which is deprecated, and resolvesfalsewhen neither is available. - A failed copy neither changes
copiednor interrupts a pending reset.
Example
The following example copies the text in the input and shows feedback with the default resetTimeout.
import { useState } from "react";
import { useCopyToClipboard } from "@lilib/hooks";
function Example() {
const [text, setText] = useState("Hello, @lilib/hooks!");
const [copied, copy] = useCopyToClipboard();
return (
<div>
<input value={text} onChange={(event) => setText(event.target.value)} />{" "}
<button onClick={() => copy(text)}>{copied ? "Copied!" : "Copy"}</button>
</div>
);
}
export default Example;