JAVASCRIPT

How to implement a custom useInterval hook for repeating actions

Create a `useInterval` React hook to execute a function repeatedly at specified intervals, ideal for countdowns, animations, or periodic data fetching.

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) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

// Example Usage:
// function Counter() {
//   const [count, setCount] = useState(0);
//   const [isRunning, setIsRunning] = useState(true);

//   useInterval(() => {
//     if (isRunning) {
//       setCount(count + 1);
//     }
//   }, 1000); // Update every 1 second

//   return (
//     <div>
//       <h1>Count: {count}</h1>
//       <button onClick={() => setIsRunning(!isRunning)}>
//         {isRunning ? 'Pause' : 'Resume'}
//       </button>
//     </div>
//   );
// }
How it works: The `useInterval` hook provides a robust way to execute a given `callback` function repeatedly after a specified `delay`. It uses `useRef` to maintain a stable reference to the latest `callback` function, preventing issues with stale closures and ensuring that the most up-to-date logic is always run. The `useEffect` hook handles the setup and teardown of the `setInterval` timer, ensuring efficient resource management and allowing the interval to be dynamically paused or started by setting `delay` to `null` or a number, respectively.

Need help integrating this into your project?

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

Hire DigitalCodeLabs