Use Clipboard

A hook to copy text to clipboard and track if copy action was successful

Preview

Installation

CLI

npx shadcn@latest add https://kelvinmai.io/r/use-clipboard.json

Manual

Copy and paste the following code into your project

hooks/use-clipboard.ts
'use client';
import * as React from 'react';
type CopyFn = (text: string) => Promise<boolean>;
export const useClipboard = (delay = 2000): [CopyFn, boolean] => {
const [copied, setCopied] = React.useState(false);
React.useEffect(() => {
if (!copied) {
return;
}
const timer = setTimeout(() => {
setCopied(false);
}, delay);
return () => clearTimeout(timer);
}, [copied, delay]);
const copy = React.useCallback(async (text: string) => {
if (!navigator?.clipboard) {
console.warn('Clipboard not supported');
return false;
}
try {
await navigator.clipboard.writeText(text);
setCopied(true);
return true;
} catch (error) {
console.warn('Copy failed', error);
return false;
}
}, []);
return [copy, copied];
};

Update the import paths to match your project setup

Usage

import { useMount } from '@/hooks/use-mounted';
const mounted = useMounted();

API Reference

Parameters

NameTypeDefaultDescription
delay?
number
2000
Time in milliseconds to reset copy value

Returns

The useClipboard hook returns a tuple with the following elements:

NameTypeDescription
copy
(text: string) => Promise<boolean>
Function to copy text to clipboard.
copied
boolean
Indicates if last copy was successful, resetting after the delay.