Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Last active October 30, 2020 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fostyfost/fc7fc7b699e3fe5fdfaee1f0d8f8b497 to your computer and use it in GitHub Desktop.
Save fostyfost/fc7fc7b699e3fe5fdfaee1f0d8f8b497 to your computer and use it in GitHub Desktop.
useInterval react hook
import { useEffect, useRef } from 'react';
export const useInterval = (callback: () => void, timeout?: number): void => {
const intervalId = useRef<number>();
const savedCallback = useRef<() => void>();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (timeout && timeout > 0) {
const tick = (): void => {
if (savedCallback && typeof savedCallback.current === 'function') {
savedCallback.current();
}
};
intervalId.current = setInterval(tick, timeout);
}
return (): void => {
if (intervalId.current) {
clearInterval(intervalId.current);
}
};
}, [timeout]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment