Created
March 26, 2023 04:32
-
-
Save kingisaac95/012375f88d420f294a4d01504563f138 to your computer and use it in GitHub Desktop.
Recursively calls the provided action while caller component is mounted
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 React, { useCallback, useEffect, useRef } from "react"; | |
function usePolling(action, delay) { | |
const timeoutId = useRef(null); | |
const isComponentMounted = useRef(false); | |
const handlePolling = useCallback(() => { | |
action().then(() => { | |
if (isComponentMounted.current) { | |
timeoutId.current = setTimeout(handlePolling, delay); | |
} | |
}); | |
}, [action, delay]); | |
useEffect(() => { | |
isComponentMounted.current = true; | |
// Initiate polling action | |
handlePolling(); | |
return () => { | |
clearTimeout(timeoutId.current); | |
isComponentMounted.current = false; | |
}; | |
}, [handlePolling]); | |
} | |
export default usePolling; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment