DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Using a Custom `useInterval` Hook in React

In React applications, it’s common to run repeated tasks at regular intervals, such as polling an API, updating a clock, or triggering animations. While JavaScript provides setInterval, using it directly in React can lead to issues with cleanup and stale closures when state or props change.

Creating a custom hook like useInterval makes this process cleaner, reusable, and safer.


The Code

import React, { useEffect } from "react";

const useInterval = (fun, timeOut) => {
  useEffect(() => {
    const intervalFunction = setInterval(() => {
      fun();
    }, timeOut * 1000);

    return () => {
      clearInterval(intervalFunction);
    };
  }, [fun, timeOut]);
};

function App() {
  useInterval(() => {
    console.log("Hi");
  }, 5); // runs every 5 seconds

  return <div>App</div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

How It Works

1. Custom Hook: useInterval

const useInterval = (fun, timeOut) => { ... }
Enter fullscreen mode Exit fullscreen mode
  • fun → The callback function to run at each interval.
  • timeOut → The interval duration in seconds.
  • Inside useEffect, a setInterval is created to call fun every timeOut seconds.
  • Returning a cleanup function with clearInterval ensures the interval is stopped when the component unmounts or dependencies change.

2. Dependency Array

useEffect(() => { ... }, [fun, timeOut]);
Enter fullscreen mode Exit fullscreen mode
  • Ensures that if fun or timeOut changes, the old interval is cleared and a new interval is set up with the updated values.
  • This is important if your callback uses state or if the interval duration needs to change dynamically.

3. Using the Hook in a Component

function App() {
  useInterval(() => {
    console.log("Hi");
  }, 5); // runs every 5 seconds

  return <div>App</div>;
}
Enter fullscreen mode Exit fullscreen mode
  • The hook is called inside the component, just like a normal React hook.
  • Every 5 seconds, "Hi" is logged to the console.
  • If the component unmounts, the interval is automatically cleaned up.

Advantages of This Approach

  1. Reusability – Use the same hook in multiple components without rewriting interval logic.
  2. Automatic cleanup – Prevents memory leaks by clearing intervals on unmount or dependency changes.
  3. Dynamic intervals – Works with changing callback functions and timeout durations.
  4. Cleaner code – No need to manually manage intervals inside useEffect in every component.

Real-World Use Cases

  • Polling APIs for new data in dashboards or chat apps.
  • Countdown timers or clock updates.
  • Animating components or triggering periodic visual changes.
  • Background tasks that require repeated execution.

Conclusion

The useInterval hook is a simple yet powerful tool in React. It wraps setInterval inside a React-friendly pattern that handles dynamic dependencies and automatic cleanup, making your repeated tasks more reliable and your code more maintainable.

Top comments (0)