JAVASCRIPT
Implementing Repeating Actions with useInterval Hook
Build a custom `useInterval` React hook to execute a callback function repeatedly after a fixed delay, similar to `setInterval` but with clean React lifecycle management.
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) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]); // Re-run if delay changes
}
// Example Usage:
/*
function Timer() {
const [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000); // Increment every second
return <h1>{count}</h1>;
}
*/
How it works: The `useInterval` hook takes a `callback` function and a `delay` in milliseconds. It uses `useRef` to store the latest version of the `callback` function, ensuring that the interval always calls the most up-to-date function without requiring the interval to be cleared and re-set on every render. The second `useEffect` sets up the `setInterval` and clears it (`clearInterval`) when the component unmounts or when the `delay` changes, effectively managing the timer's lifecycle within React.