usePollingUpdate – React Hook for polling on interval

A simple hook to poll a server for updates every n milliseconds, and remove itself on unmount.

usePollingUpdate will call pollingFunction every interval milliseconds, and clean up after itself.

// usePollingUpdate.js

import { useEffect, useState } from "react";

const usePollingUpdate = (pollingFunction, interval) => {
  const [ subscription, setSubscription ] = useState(null);
  useEffect(() => {
    const id = setInterval(pollingFunction, interval)
    setSubscription(id)
    return () => {
      if(subscription){
        clearInterval(subscription);
      }
    }
  }, [])
}


export default usePollingUpdate;

// in the component
import usePollingUpdate from './hooks/usePollingUpdate';

// list items is the function to query the API. 15000 polls the server every 15s.
usePollingUpdate(() => listItems(1, true), 15000);