· 5 min read

React Custom Hook: useClipboard

The useClipboard hook simplifies the process of integrating copy-to-clipboard functionality into your React applications, leveraging the modern Clipboard API.

Streamline copy-to-clipboard functionality in your React applications with the powerful useClipboard hook. Learn how to implement and utilize this hook effectively.

In today’s web applications, the ability to copy text or data to the user’s clipboard is a common requirement. While this functionality can be achieved using various methods, the introduction of the Clipboard API in modern browsers has made it easier to implement. However, dealing with the Clipboard API directly can be cumbersome, especially when it comes to handling different browser scenarios and edge cases.

Creating the useClipboard hook – a custom React hook that abstracts away the complexities of working with the Clipboard API and provides a simple, reusable interface for copy-to-clipboard functionality.

Implementation

Here’s the implementation of the useClipboard hook:

import { useState } from 'react';

export function useClipboard({ timeout = 2000 } = {}) {
  const [error, setError] = useState<Error | null>(null);
  const [copied, setCopied] = useState(false);
  const [copyTimeout, setCopyTimeout] = useState<number | null>(null);

  const handleCopyResult = (value: boolean) => {
    window.clearTimeout(copyTimeout!);
    setCopyTimeout(window.setTimeout(() => setCopied(false), timeout));
    setCopied(value);
  };

  const copy = (valueToCopy: any) => {
    if ('clipboard' in navigator) {
      navigator.clipboard
        .writeText(valueToCopy)
        .then(() => handleCopyResult(true))
        .catch((err) => setError(err));
    } else {
      setError(new Error('useClipboard: navigator.clipboard is not supported'));
    }
  };

  const reset = () => {
    setCopied(false);
    setError(null);
    window.clearTimeout(copyTimeout!);
  };

  return { copy, reset, error, copied };
}

Let’s break down the code:

  1. Importing Dependencies: The hook imports the useState hook from the React library.
  2. Hook Definition: The useClipboard function is defined, taking an optional timeout parameter (default: 2000ms) that determines how long the “copied” state should remain true after a successful copy operation.
  3. State Management: The hook uses React’s useState hook to manage three pieces of state: error (to store any errors that occur during the copy operation), copied (a boolean indicating whether the content has been successfully copied to the clipboard), and copyTimeout (a reference to a timeout used to reset the copied state after the specified timeout duration).
  4. Utility Functions:
  • handleCopyResult: This function handles the result of the copy operation. It clears any existing timeout, sets a new timeout to reset the copied state after the specified timeout duration, and updates the copied state with the provided value.
  • copy: This function performs the actual copy operation. It first checks if the navigator.clipboard API is supported in the current browser. If supported, it calls navigator.clipboard.writeText with the valueToCopy and handles the promise resolution and rejection. If the API is not supported, it sets an appropriate error.
  • reset: This function resets the copied state to false, clears any existing error, and clears the copyTimeout.
  1. Return Value: The hook returns an object containing the copy, reset, error, and copied values, allowing the consumer to access and use these functionalities.

Usage

Using the useClipboard hook is straightforward. Here’s an example:

import { useClipboard } from './useClipboard';

function CopyButton() {
  const { copy, reset, error, copied } = useClipboard({ timeout: 3000 });

  const handleCopy = () => {
    copy('Hello, World!');
  };

  return (
    <div>
      <button onClick={handleCopy}>Copy Text</button>
      {copied && <p>Text copied to clipboard!</p>}
      {error && <p>Error: {error.message}</p>}
      <button onClick={reset}>Reset</button>
    </div>
  );
}

In this example, we import the useClipboard hook and destructure its returned values (copy, reset, error, and copied). We pass a timeout value of 3000ms (3 seconds) to the hook.

The handleCopy function is called when the “Copy Text” button is clicked, invoking the copy function with the value 'Hello, World!'. If the copy operation is successful, the copied state will be set to true, and a message will be displayed indicating that the text has been copied to the clipboard.

If an error occurs during the copy operation, the error state will be set with the corresponding error message, which can be displayed to the user.

The “Reset” button calls the reset function, resetting the copied and error states to their initial values.

Benefits

Using the useClipboard hook can provide several benefits in your React applications:

  1. Simplified Clipboard Integration: The hook abstracts away the complexities of working with the Clipboard API, providing a simple and reusable interface for copy-to-clipboard functionality.
  2. Cross-Browser Compatibility: The hook handles browser support for the Clipboard API, ensuring consistent behavior across different browsers and fallback mechanisms for unsupported environments.
  3. Customizable Timeout: The hook allows you to customize the duration for which the “copied” state remains true, providing flexibility in handling user feedback and UI updates.
  4. Error Handling: The hook provides built-in error handling, making it easier to manage and display errors related to the copy operation.
  5. Reusability: By encapsulating the copy-to-clipboard functionality in a hook, you can easily reuse it across multiple components and projects, promoting code reusability and maintainability.

Conclusion

The useClipboard hook is a powerful addition to your React development toolkit, simplifying the integration of copy-to-clipboard functionality in your applications. By leveraging the modern Clipboard API and providing a user-friendly interface, this hook streamlines the process of copying data to the user’s clipboard, enhancing the overall user experience.

Whether you’re building a text-editing application, a code snippet sharing platform, or any other application that requires copy-to-clipboard functionality, the useClipboard hook can be a valuable asset in your development workflow. Embrace the power of custom hooks and elevate your React applications to new heights!

Need a React Developer? Let’s Work Together!

Are you impressed by the usePrevious hook and looking for an experienced React developer to bring your project to life?

Feel free to reach out to me here - Contact Seerat Awan to discuss your project and get a quote.

With a deep understanding of React and other javascript based frameworks, I can help you build high-performance, efficient, and user-friendly applications tailored to your specific needs.

Don’t hesitate to get in touch – I’m excited to hear about your project and explore how we can collaborate to create exceptional React applications together!

Seerat Awan

Tech Enthusiast | Frontend Developer

@seeratawan01

Subscribe to my newsletter to get the latest updates on my blog.

Back to Blog