Skip to content

Instantly share code, notes, and snippets.

@kingisaac95
Created March 26, 2023 04:32
Show Gist options
  • Save kingisaac95/012375f88d420f294a4d01504563f138 to your computer and use it in GitHub Desktop.
Save kingisaac95/012375f88d420f294a4d01504563f138 to your computer and use it in GitHub Desktop.
Recursively calls the provided action while caller component is mounted
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