Last active
December 30, 2021 20:17
-
-
Save codemile/749dfc01c5f4a0a0ec84522619de0de6 to your computer and use it in GitHub Desktop.
A interval hook you can use in your ReactJS projects
This file contains hidden or 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 {DependencyList, useEffect, useMemo} from 'react'; | |
export const useInterval = ( | |
callback: () => void, | |
ms: number, | |
deps: DependencyList | |
) => { | |
const all_deps = useMemo( | |
() => [callback, ms, ...deps], | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
[callback, ms, deps] | |
); | |
useEffect(() => { | |
const id = setInterval(() => callback(), ms); | |
return () => clearInterval(id); | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, all_deps); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment