JAVASCRIPT

Simplify setInterval with useInterval React Hook

Create a robust useInterval React hook to manage timed actions, automatically handling interval setup and cleanup for recurring tasks.

import { useEffect, useRef } from 'react';

const 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]);
};

export default useInterval;
How it works: This `useInterval` hook provides a more React-friendly way to use `setInterval`. It abstracts away the complexity of setting up and tearing down intervals, making it ideal for tasks like countdowns or polling. The hook takes a `callback` function and a `delay` in milliseconds. It uses a `useRef` to keep track of the latest callback without causing the interval to reset if the callback changes. The `useEffect` hook then sets up the interval, and its cleanup function ensures `clearInterval` is called when the component unmounts or the delay changes, preventing memory leaks and unwanted behavior.

Need help integrating this into your project?

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

Hire DigitalCodeLabs