Skip to content

Instantly share code, notes, and snippets.

@manix84
Last active February 8, 2025 18:11
Show Gist options
  • Save manix84/994b4c73a7cee3453e2a7c44973724c5 to your computer and use it in GitHub Desktop.
Save manix84/994b4c73a7cee3453e2a7c44973724c5 to your computer and use it in GitHub Desktop.
A react hook for setTimeout
/**
This code is licensed under the terms of the MIT license
*/
import { useEffect, useRef } from 'react';
export const useTimeout = (callback: () => void, delay: number): [() => void] => {
const timeoutIdRef = useRef<number | null>(null);
useEffect(() => {
timeoutIdRef.current = window.setTimeout(callback, delay);
return () => {
if (timeoutIdRef.current !== null) {
window.clearTimeout(timeoutIdRef.current);
}
};
}, [callback, delay]);
const clearTimeout = () => {
if (timeoutIdRef.current !== null) {
window.clearTimeout(timeoutIdRef.current);
timeoutIdRef.current = null;
}
};
return [clearTimeout];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment