Skip to content

Instantly share code, notes, and snippets.

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