Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active June 12, 2023 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazy4groovy/ee00a7d8d53a3c9b36561a187f7bee37 to your computer and use it in GitHub Desktop.
Save crazy4groovy/ee00a7d8d53a3c9b36561a187f7bee37 to your computer and use it in GitHub Desktop.
A simple hook to implement interval polling of any thunk (ReactJS)
import React, { useState } from 'react';
import usePolling from './usePolling';
import ...
const useCustomPolling = () => {
const [state, setState] = useState()
const cb = async (cancelPolling) => {
// do some logics here... whatever...
if (!isDone) return; // Continue polling
// do some more logics here...
cancelPolling(); // Stop polling
};
const cancelPolling = usePolling(cb, 5000);
return { state, cancelPolling };
};
import { useEffect, useRef } from 'react';
const usePolling = (callback, delay) => {
const savedCallback = useRef();
const intervalRef = useRef();
const cleanup = () => clearInterval(intervalRef.current);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
const tick = () => savedCallback.current(cleanup);
if (delay != null) {
intervalRef.current = setInterval(tick, delay);
}
tick();
return cleanup;
}, [delay]);
return cleanup;
};
export default usePolling;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment