mastodon/app/javascript/hooks/useTimeout.ts
Eugen Rochko e89317d4c1
Add hover cards in web UI (#30754)
Co-authored-by: Renaud Chaput <renchap@gmail.com>
2024-06-26 19:33:38 +00:00

30 lines
637 B
TypeScript

import { useRef, useCallback, useEffect } from 'react';
export const useTimeout = () => {
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
const set = useCallback((callback: () => void, delay: number) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(callback, delay);
}, []);
const cancel = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = undefined;
}
}, []);
useEffect(
() => () => {
cancel();
},
[cancel],
);
return [set, cancel] as const;
};