Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created July 8, 2021 08:15
Show Gist options
  • Save tjinlag/6249d2e1f58b981db0dc2571eae10dca to your computer and use it in GitHub Desktop.
Save tjinlag/6249d2e1f58b981db0dc2571eae10dca to your computer and use it in GitHub Desktop.
custom hook: useToastContent - using for toast a message, and then automatically hide it (after a timeout, eg: 2s)
export const useToastContent = (timeout = 2e3) => {
const [content, setContent] = useState('');
const timer = useRef();
useEffect(() => {
return () => {
if (timer && timer.current) {
clearTimeout(timer.current);
}
}
}, []);
const toast = (value) => {
setContent(value);
timer.current = setTimeout(() => {
setContent('');
}, timeout);
}
const close = () => {
setContent('');
if (timer && timer.current) {
clearTimeout(timeout.current);
}
}
return [content, toast, close];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment