React simple polling custom hook usePollingEffect.

A remarkably simple polling function can be implemented with React hooks.

There are two main differences between a usePollingEffect and a useInterval custom hook. First, the polling effect must execute as soon as it is called (contrary to an interval which would trigger the first call only after the specified time has passed). Second, we can’t trigger a new call if the previous call hasn’t finalized, the polling hook must wait until the previous call was finalized while the interval shouldn’t care.

This hook tries to execute the async callback. Then it creates a timeout with the expected interval between calls. This takes care of immediately calling the polling function and waiting until the previous call has finalized before creating a timeout.

Usage

onCleanUp is a function executed during the cleanup phase of useEffect.

We can also use it in conjunction with useMountedState to prevent the Can’t perform a React state update on an unmounted component error:

Enhancements

If you are looking into stopping a polling mechanism, you might also want to cancel a fetch request by Using AbortController with Fetch API and ReactJS:

Furthermore, we could add a mechanism to kill the poll if we needed it:

--

--

Staff Sofware Architect 2 at PayPal, M.S. in Computer Science w/specialization in Computing Systems, B.Eng. in Computer Software.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pablo Garcia

Staff Sofware Architect 2 at PayPal, M.S. in Computer Science w/specialization in Computing Systems, B.Eng. in Computer Software.