JAVASCRIPT
Implementing a Reliable `useInterval` Hook in React
Develop a `useInterval` React hook for safely executing a function repeatedly after a fixed delay, effectively handling `setInterval` logic within a functional component lifecycle.
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) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
// Example usage:
/*
function Timer() {
const [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000); // Increment count every 1 second
return <p>Count: {count}</p>;
}
*/
How it works: The `useInterval` hook provides a declarative way to use `setInterval` in React components, addressing common issues like stale closures. It uses `useRef` to store the latest `callback` function, ensuring that the interval always calls the most up-to-date version of the function without needing to restart the interval. The `useEffect` hook then sets up and tears down the `setInterval` using the `delay`, effectively managing the interval's lifecycle within the component.