JAVASCRIPT
Creating a useInterval Hook for Periodic Actions
Implement a custom `useInterval` React hook to easily run functions periodically with a fixed delay, perfect for timers, animations, or data polling.
function useInterval(callback, delay) {
const savedCallback = React.useRef();
// Remember the latest callback.
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
React.useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
// Example usage:
function Counter() {
const [count, setCount] = React.useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000); // Update count every 1 second
return React.createElement("h1", null, count);
}
How it works: The `useInterval` hook provides a clean way to execute a function repeatedly after a specified delay. It uses `useRef` to keep the callback function stable across re-renders, preventing the interval from being cleared and reset unnecessarily when the component re-renders. The `useEffect` hook manages the `setInterval` and `clearInterval` lifecycle, ensuring the interval starts when the component mounts and cleans up when it unmounts or the delay changes. This pattern is ideal for building custom timers, animations, or polling mechanisms efficiently.