JAVASCRIPT
useInterval Hook for Reliable Interval Management
Create a robust `useInterval` React hook to safely manage `setInterval` functions, preventing common closure issues and ensuring proper cleanup for animations, timers, and data polling.
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 1 second
// return <div>Timer: {count}</div>;
// }
How it works: The `useInterval` hook provides a reliable way to use `setInterval` in React components, addressing common issues with stale closures. It uses a `useRef` to always hold the latest version of the `callback` function without re-creating the interval. The `useEffect` hook then sets up and tears down the interval based on the `delay`. This ensures that your callback always has access to the most current state and props, making it ideal for animations, polling, or any time-based repetitive task.