JAVASCRIPT

React useInterval Hook for Repeating Actions

Create a flexible useInterval hook in React to execute a function repeatedly after a specified delay, ideal for animations, data polling, or countdowns.

import { useEffect, useRef } from 'react';

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      const id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}
How it works: The `useInterval` hook provides a declarative way to set up a `setInterval` that automatically clears itself on unmount. It stores the `callback` in a `useRef` to ensure that the interval always uses the latest version of the callback without needing to restart the interval itself, preventing stale closures and unnecessary re-renders.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs