React simple polling custom hook usePollingEffect
React simple polling custom hook usePollingEffect
custom hook
usePollingEffect.
Pablo Garcia
·
Follow
2 min read
29
care.
function usePollingEffect(
asyncCallback,
dependencies = [],
onCleanUp = () => {}
} = {},
) {
try {
await asyncCallback()
} finally {
pollingCallback,
interval
)
})()
return () => {
clearTimeout(timeoutIdRef.current)
onCleanUp()
}, [...dependencies, interval])
}
This hook tries to execute the async callback. Then it
Usage
usePollingEffect(
[],
)
onCleanUp is a function executed during the cleanup
phase of useEffect.
usePollingEffect(
[],
{ interval: 3000 }
Enhancements
If you are looking into stopping a polling mechanism,
usePollingEffect(
async () => await healthCheck(),
[],
function usePollingEffect(...) {
// ...
useEffect(() => {
if(dead) {
return
// ...
}, [..., dead])
React
Reactjs
Polling
Hooks
JavaScript