npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

use-copy-clipboard-react

v1.0.0

Published

Production-ready React 18 & 19 hook to copy text to clipboard with timeout auto-reset and legacy browser fallback.

Readme

📋 use-copy-clipboard-react

Production-ready, zero-dependency React 18 & 19 hook to copy text to clipboard with automatic reset timers, status feedback, and legacy browser fallback.

npm version License: MIT Sponsor React 18 & 19 TypeScript


✨ Features

  • ⏱️ Automatic Feedback Timer — isCopied automatically toggles to true on copy and resets to false after a configurable duration (default: 2000ms).
  • 🛡️ Universal Compatibility Fallback — Tries modern navigator.clipboard.writeText first; seamlessly falls back to hidden document.execCommand('copy') on non-HTTPS origins or legacy webviews.
  • 🧹 Unmount & Leak Safe — Automatically cleans up pending reset timeouts when the component unmounts.
  • ⚡ Zero Dependencies — Ultra-lightweight (< 1 KB minified).
  • 🧰 Standalone Utility Included — Exports pure async copyToClipboard(text) function for use outside of React component lifecycles.
  • 📦 Dual ESM & CommonJS — Works out-of-the-box in Next.js (App & Pages Router), Vite, Remix, Gatsby, and React Native Web.

📥 Installation

# npm
npm install use-copy-clipboard-react

# pnpm
pnpm add use-copy-clipboard-react

# yarn
yarn add use-copy-clipboard-react

# bun
bun add use-copy-clipboard-react

🚀 Usage & Real-World Examples

1. Basic Copy Button

import React from 'react';
import { useClipboard } from 'use-copy-clipboard-react';

export function ShareLink({ url }: { url: string }) {
  const { copy, isCopied } = useClipboard({ timeoutMs: 2500 });

  return (
    <div className="flex items-center gap-2">
      <input readOnly value={url} className="border p-2 rounded" />
      <button
        onClick={() => copy(url)}
        className="px-4 py-2 bg-blue-600 text-white rounded font-medium"
      >
        {isCopied ? 'Copied! 🎉' : 'Copy Link'}
      </button>
    </div>
  );
}

2. Code Block with Notification Callbacks

import React from 'react';
import { useClipboard } from 'use-copy-clipboard-react';

export function CodeSnippet({ code }: { code: string }) {
  const { copy, isCopied, error } = useClipboard({
    timeoutMs: 2000,
    onSuccess: (text) => console.log('Successfully copied:', text),
    onError: (err) => console.error('Failed to copy snippet:', err),
  });

  return (
    <div className="relative code-card">
      <button
        onClick={() => copy(code)}
        className="absolute top-2 right-2 px-2 py-1 bg-gray-800 text-xs text-white rounded"
      >
        {isCopied ? '✔ Copied' : 'Copy'}
      </button>
      <pre>
        <code>{code}</code>
      </pre>
      {error && <p className="text-red-500 text-xs">Error: {error.message}</p>}
    </div>
  );
}

3. Using Standalone copyToClipboard() in Event Handlers

If you want to copy text inside an async API handler without creating React state:

import { copyToClipboard } from 'use-copy-clipboard-react';

async function handleGenerateShareToken() {
  const token = await generateApiToken();
  const success = await copyToClipboard(token);

  if (success) {
    alert('Token generated and copied to clipboard!');
  } else {
    prompt('Could not copy automatically. Please copy manually:', token);
  }
}

📖 API Reference

useClipboard(options?)

Custom hook providing reactive clipboard state and actions.

Options (UseClipboardOptions):

| Option | Type | Default | Description | |---|---|---|---| | timeoutMs | number | 2000 | Duration before isCopied resets back to false | | onSuccess | (text: string) => void | undefined | Callback invoked immediately upon successful copy | | onError | (error: Error) => void | undefined | Callback invoked if clipboard access fails |

Return Value:

| Property | Type | Description | |---|---|---| | copy | (text: string) => Promise<boolean> | Asynchronously copies text to clipboard | | isCopied | boolean | true while the success feedback timer is active | | error | Error \| null | Error object if the last copy attempt failed | | reset | () => void | Clears active timeout and resets state immediately |


copyToClipboard(text)

Pure asynchronous helper function to copy a string to system clipboard.

  • Parameters:
    • text (string): The text to copy.
  • Returns: Promise<boolean> (true if successful, false otherwise).

💖 Support the Project

If use-copy-clipboard-react made sharing in your web apps smooth and reliable, please consider sponsoring:

👉 Sponsor @Piratha97 on GitHub Sponsors


📄 License

MIT © 2026 Pirapaakaran Pirathapan