aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-timeout/use-timeout.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/hooks/use-timeout/use-timeout.ts')
-rw-r--r--src/utils/hooks/use-timeout/use-timeout.ts29
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;
+};