Skip to content

Instantly share code, notes, and snippets.

@Sachin-chaurasiya
Created March 19, 2023 06:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Sachin-chaurasiya/56154e66a68f077bc1d858ca4d3c92da to your computer and use it in GitHub Desktop.
Custom hook for copy to clipboard functionality
import { useCallback, useEffect, useState } from 'react';
/**
* React hook to copy text to clipboard
* @param value the text to copy
* @param timeout delay (in ms) to switch back to initial state once copied.
* @param callBack execute when content is copied to clipboard
*/
export const useClipboard = (
value: string,
timeout = 1500,
callBack?: () => void
) => {
// local state
const [hasCopied, setHasCopied] = useState(false);
const [valueState, setValueState] = useState(value);
// handlers
const handleCopy = useCallback(async () => {
try {
await navigator.clipboard.writeText(valueState);
setHasCopied(true);
callBack && callBack();
} catch (error) {
setHasCopied(false);
}
}, [valueState]);
// side effects
useEffect(() => setValueState(value), [value]);
useEffect(() => {
let timeoutId: number | null = null;
if (hasCopied) {
timeoutId = Number(
setTimeout(() => {
setHasCopied(false);
}, timeout)
);
}
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
};
}, [timeout, hasCopied]);
return {
onCopyToClipBoard: handleCopy,
hasCopied,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment