snippet

useCopyToClipboard

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];
};

The hook situation

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:

  1. A value that lets you know if copying has been successful. This is a boolean value and it is false by default.
  2. A function that lets you copy text to the clipboard

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.

How to use the useCopyToClipboard hook?

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>}
    </>
  );
};

Last updated December 11th, 2022