Last active
July 15, 2023 03:16
-
-
Save adam-zethraeus/99956357f5669491dc89bf5261126e3a to your computer and use it in GitHub Desktop.
usePolling React hook
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, useState } from "react"; | |
const usePolling = (interval = null, pollingFunction, deps = []) => { | |
const [subscription, setSubscription] = useState(null); | |
useEffect(() => { | |
if (!!interval) { | |
const id = setInterval(pollingFunction, interval); | |
setSubscription(id); | |
} | |
return () => { | |
if (subscription) { | |
clearInterval(subscription); | |
} | |
}; | |
}, [...deps]); | |
}; | |
export { usePolling }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment