← Back to all snippets
JAVASCRIPT

Implement a Repeating Interval with `useInterval` React Hook

Create a custom React `useInterval` hook to easily manage `setInterval` logic within your components, ensuring proper cleanup on unmount and preventing memory leaks.

import React, { 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 TimerComponent() {
  const [count, setCount] = React.useState(0);

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

  return (
    <div>
      <h1>Count: {count}</h1>
    </div>
  );
}
How it works: The `useInterval` hook provides a clean way to use `setInterval` in React components. It uses `useRef` to keep a stable reference to the callback function, preventing re-renders from breaking the interval. The `useEffect` hook handles setting up and clearing the interval when the `delay` changes or the component unmounts, ensuring proper resource management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs