JAVASCRIPT
Declarative setInterval Hook for React
A reliable custom React hook to easily manage `setInterval` functionality, preventing common closure issues and ensuring proper cleanup.
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 every second
//
// return <h1>{count}</h1>;
// }
How it works: The `useInterval` hook provides a safe and declarative way to use `setInterval` in React. It stores the `callback` function in a `useRef` to always access the latest version, avoiding stale closures. A `useEffect` then manages the interval, setting it up with `setInterval` when `delay` is not null and clearing it with `clearInterval` on unmount or when `delay` changes, ensuring proper lifecycle management.