diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-11-02 15:33:29 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-11-11 18:15:27 +0100 |
| commit | e2daf7f81789c54b23ade72bd164492e7304d375 (patch) | |
| tree | 4d515b6b113dcc5bba6ff08ca5c6e7ddc8094e02 /src/utils/hooks/use-timeout/use-timeout.ts | |
| parent | 1e4b48aa075e6131a7244cd4726ddb5ba75fcecf (diff) | |
feat(hooks): add an useTimeout hook
Diffstat (limited to 'src/utils/hooks/use-timeout/use-timeout.ts')
| -rw-r--r-- | src/utils/hooks/use-timeout/use-timeout.ts | 29 |
1 files changed, 29 insertions, 0 deletions
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<UseTimeoutId>} The timeout id. + */ +export const useTimeout = ( + callback: UseTimeoutCallback, + delay = 0 +): MutableRefObject<UseTimeoutId> => { + const idRef = useRef<UseTimeoutId>(undefined); + + useEffect(() => { + idRef.current = setTimeout(() => callback(), delay); + + return () => { + clearTimeout(idRef.current); + }; + }, [callback, delay]); + + return idRef; +}; |
