JAVASCRIPT

React Hook: useInterval for Repeating Actions

Implement a custom React hook `useInterval` to execute a function repeatedly at a set time interval, useful for timers, polling, or animations in your components.

import { useEffect, useRef } from 'react';

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

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    const tick = () => {
      savedCallback.current();
    };
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
};

export default useInterval;
How it works: The `useInterval` hook allows you to run a function `callback` every `delay` milliseconds. It uses `useRef` to store the latest `callback` function, preventing stale closures. The `useEffect` hook then sets up and tears down the `setInterval`, ensuring it's cleaned up when the component unmounts or the `delay` changes. This is invaluable for features requiring periodic updates, like countdown timers or data polling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs