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;
How It Works
1. Custom Hook: useInterval
const useInterval = (fun, timeOut) => { ... }
-
fun
→ The callback function to run at each interval. -
timeOut
→ The interval duration in seconds. - Inside
useEffect
, asetInterval
is created to callfun
everytimeOut
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]);
- Ensures that if
fun
ortimeOut
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>;
}
- 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
- ✅ Reusability – Use the same hook in multiple components without rewriting interval logic.
- ✅ Automatic cleanup – Prevents memory leaks by clearing intervals on unmount or dependency changes.
- ✅ Dynamic intervals – Works with changing callback functions and timeout durations.
- ✅ 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)