JAVASCRIPT
Safely Manage `setInterval` with a Custom React Hook
Implement a `useInterval` hook to safely execute a function repeatedly with a fixed time delay, ensuring proper cleanup and preventing common `setInterval` pitfalls in React.
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() {
if (savedCallback.current) {
savedCallback.current();
}
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
export default useInterval;
// Example Usage:
/*
function Timer() {
const [count, setCount] = useState(0);
useInterval(() => {
// Your custom logic here
setCount(count + 1);
}, 1000); // Run every 1000ms (1 second)
return <h1>{count}</h1>;
}
*/
How it works: The `useInterval` hook provides a robust way to use `setInterval` in React. It stores the latest `callback` in a `useRef` to ensure the interval always executes the most current function without re-creating the interval itself on every render. The second `useEffect` sets up the `setInterval` only when `delay` is not `null`, and its cleanup function ensures `clearInterval` is called, preventing memory leaks and unwanted behavior when the component unmounts or the `delay` changes.