JAVASCRIPT

Execute a Function Repeatedly at Intervals

A custom React hook that enables executing a given function repeatedly after a specified delay, similar to `setInterval`, but with a clean lifecycle management.

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:
// import React, { useState } from 'react';
// function Counter() {
//   const [count, setCount] = useState(0);

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

//   return <h1>{count}</h1>;
// }
How it works: This hook allows you to set up an interval that repeatedly calls a provided `callback` function after a specified `delay`. It uses a `useRef` to ensure the callback always refers to the latest version without causing the interval to reset. The `useEffect` hook effectively manages the `setInterval` and `clearInterval` lifecycle, preventing memory leaks and ensuring the interval runs only when the component is mounted.

Need help integrating this into your project?

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

Hire DigitalCodeLabs