snippet
useCopyToClipboard
snippet
useCopyToClipboard
Last updated December 11th, 2022
Have you ever wanted to copy something to the clipboard and also show a notification upon success? This handy little hook can help you with that!
The useCopyToClipboard hook provides two things:
Upon copy success, the copy function will set the result state to true. We are using a useEffect
to monitor when the result
state changes as after 3 seconds this result state is set back to false. This 3 seconds is the default and can be changed by passing the time in milliseconds into the useCopyToClipboard hook.
import { useState, useCallback, useEffect } from "react";
const useCopyToClipboard = (timeOut = 3000) => {
const [result, setResult] = useState(false);
const copyFn = useCallback(async (copyText) => {
try {
await navigator.clipboard.writeText(copyText);
setResult(true);
} catch {
setResult(false);
}
}, []);
useEffect(() => {
let timer;
if (result) {
timer = setTimeout(() => setResult(false), timeOut);
}
return () => {
if (timer) {
clearTimeout(timer);
}
};
}, [timeOut, result]);
return [result, copyFn];
};
import useCopyToClipboard from "./useCopyToClipboard";
const App = () => {
const [isCopied, copyFn] = useCopyToClipboard();
return (
<>
<button onClick={() => copyFn("text to be copied")}>Copy the link</button>
{isCopied && <p>Copied!</p>}
</>
);
};