useClipboard
Copy text to the clipboard.
Import
TypeScript
import { useClipboard } from '@/hooks';API
Signature
useClipboard(options?) → { copy, copied, error, reset }
When to use
Use useClipboard instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Browser utilities are SSR-gated; lifecycle hooks are safe.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useClipboardEditor
function CopyLink({ url }: { url: string }) { const { copy, copied, error } = useClipboard(); return ( <button onClick={() => void copy(url)}> {copied ? 'Copied!' : error ? error.message : 'Copy link'} </button> ); }
Preview
Implementation source
Full library source for useClipboard — copy into your project when you are not installing a package yet.
hooks/utility/useClipboard.ts
import { useCallback, useState } from 'react';
import { isBrowser } from './isBrowser';
import { useTimeoutFn } from '../timer/useTimeoutFn';
export interface UseClipboardOptions {
/** How long `copied` stays true (ms). @default 2000 */
timeout?: number;
}
export interface UseClipboardReturn {
copy: (text: string) => Promise<boolean>;
copied: boolean;
error: Error | null;
reset: () => void;
}
/** Clipboard write helper with success/error feedback. */
export function useClipboard(
options: UseClipboardOptions = {},
): UseClipboardReturn {
const { timeout = 2000 } = options;
const [copied, setCopied] = useState(false);
const [error, setError] = useState<Error | null>(null);
const { start, clear } = useTimeoutFn(() => setCopied(false), timeout);
const reset = useCallback(() => {
setCopied(false);
setError(null);
clear();
}, [clear]);
const copy = useCallback(
async (text: string) => {
if (!isBrowser() || !navigator.clipboard?.writeText) {
const err = new Error('Clipboard API is unavailable');
setError(err);
setCopied(false);
return false;
}
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setError(null);
start();
return true;
} catch (e) {
const err = e instanceof Error ? e : new Error(String(e));
setError(err);
setCopied(false);
return false;
}
},
[start],
);
return { copy, copied, error, reset };
}
Copy-paste example
useClipboard.example.tsx
'use client';
import { useClipboard } from '@/hooks';
export function CopyLink({ url }: { url: string }) {
const { copy, copied, error } = useClipboard();
return (
<button onClick={() => void copy(url)}>
{copied ? 'Copied!' : error ? error.message : 'Copy link'}
</button>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Lifecycle hooks are for side effects only — not for deriving render state.
- Source of truth: open
hooks/utility/useClipboard.tsfor implementation details