JAVASCRIPT

React `useCopyToClipboard` Hook for Easy Text Copying

Provides a simple React hook to programmatically copy text to the user's clipboard, complete with state to indicate success or error and a reset mechanism.

import { useState, useCallback, useEffect } from 'react';

const useCopyToClipboard = () => {
  const [copyStatus, setCopyStatus] = useState(null); // 'success', 'error', null
  const [value, setValue] = useState(null);

  const copy = useCallback(async (textToCopy) => {
    setValue(textToCopy);
    try {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(textToCopy);
        setCopyStatus('success');
      } else {
        throw new Error('Clipboard API not available');
      }
    } catch (err) {
      console.error('Failed to copy text: ', err);
      setCopyStatus('error');
    }
  }, []);

  const reset = useCallback(() => {
    setCopyStatus(null);
    setValue(null);
  }, []);

  useEffect(() => {
    if (copyStatus === 'success' || copyStatus === 'error') {
      const timer = setTimeout(() => reset(), 2000);
      return () => clearTimeout(timer);
    }
  }, [copyStatus, reset]);

  return [value, copyStatus, copy, reset];
};

export default useCopyToClipboard;
How it works: This hook facilitates copying text to the clipboard. It leverages the `navigator.clipboard.writeText` API, updating its `copyStatus` state to reflect success or failure. An automatic reset mechanism clears the status after a short delay, providing transient feedback to the user without manual intervention. It offers a robust way to add copy functionality to your React applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs