JAVASCRIPT

Manage setInterval Safely with useInterval

Create a custom React hook, useInterval, to reliably execute a function repeatedly at fixed time intervals, automatically handling lifecycle for cleanup.

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

export default useInterval;
How it works: This useInterval hook provides a safe and easy way to use setInterval in React components. It uses useRef to keep the latest callback function without triggering re-renders, and useEffect to set up and clear the interval, ensuring proper cleanup on unmount or delay change. This prevents common issues like stale closures and memory leaks associated with raw setInterval.

Need help integrating this into your project?

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

Hire DigitalCodeLabs