From e2daf7f81789c54b23ade72bd164492e7304d375 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Thu, 2 Nov 2023 15:33:29 +0100 Subject: feat(hooks): add an useTimeout hook --- src/utils/hooks/use-timeout/use-timeout.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/utils/hooks/use-timeout/use-timeout.ts (limited to 'src/utils/hooks/use-timeout/use-timeout.ts') diff --git a/src/utils/hooks/use-timeout/use-timeout.ts b/src/utils/hooks/use-timeout/use-timeout.ts new file mode 100644 index 0000000..4d1ed47 --- /dev/null +++ b/src/utils/hooks/use-timeout/use-timeout.ts @@ -0,0 +1,29 @@ +import { type MutableRefObject, useEffect, useRef } from 'react'; + +export type UseTimeoutCallback = () => void; + +export type UseTimeoutId = string | number | NodeJS.Timeout | undefined; + +/** + * React hook to schedule the execution of a one-time callback after delay. + * + * @param {UseTimeoutCallback} callback - The callback to schedule. + * @param {number} [delay] - A delay in ms. + * @returns {MutableRefObject} The timeout id. + */ +export const useTimeout = ( + callback: UseTimeoutCallback, + delay = 0 +): MutableRefObject => { + const idRef = useRef(undefined); + + useEffect(() => { + idRef.current = setTimeout(() => callback(), delay); + + return () => { + clearTimeout(idRef.current); + }; + }, [callback, delay]); + + return idRef; +}; -- cgit v1.2.3