JAVASCRIPT
Create a Declarative useInterval Hook for React
Manage recurring functions declaratively in React components with a custom `useInterval` hook, handling cleanup and preventing stale closures.
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); // Update every second
return <h1>Count: {count}</h1>;
}
*/
How it works: The `useInterval` hook allows you to easily set up and clear `setInterval` functions in your React components in a declarative way. It uses `useRef` to persistently store the latest version of the `callback` function, preventing common issues with stale closures that can occur when using `setInterval` directly within `useEffect`. This hook is perfect for features like timers, automatic slideshows, or polling for data at regular intervals.