Last active
December 19, 2022 22:44
-
-
Save elsaulio/1b31b4a56c8e5724ddcbec673e75f85d to your computer and use it in GitHub Desktop.
A simple hook for managing intervals with React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react'; | |
/** | |
* Activate with a delay greater than zero | |
* The last callback is applied immediately | |
* | |
* Adapted from https://usehooks-ts.com/react-hook/use-interval | |
*/ | |
export function useInterval(callback: () => void, delay: number | null) { | |
const savedCallback = useRef(callback); | |
// eslint-disable-next-line no-undef | |
const interval = useRef<NodeJS.Timer | null>(null); | |
// Remember the latest callback if it changes. | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
// Set up the interval. | |
useEffect(() => { | |
if (delay && typeof delay === 'number' && delay > 0) { | |
interval.current = setInterval(() => savedCallback.current(), delay); | |
} | |
// clear the interval if delay changes | |
return () => { | |
if (interval.current) clearInterval(interval.current); | |
}; | |
}, [delay]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment