JAVASCRIPT
Manage Timed Intervals with useInterval React Hook
Learn to create a robust useInterval React hook that safely executes a callback function repeatedly after a specified delay, mimicking setInterval within React's 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(() => {
// // Your custom logic here
// setCount(count + 1);
// }, 1000); // Update every 1 second
//
// return <h1>{count}</h1>;
// }
How it works: The `useInterval` hook provides a clean and safe way to use `setInterval` within a React functional component. It takes a `callback` function and a `delay` (in milliseconds) as arguments. It uses a `useRef` to store the latest version of the `callback` to prevent stale closures. The `useEffect` then sets up the interval, clearing it when the component unmounts or the `delay` changes, ensuring that the callback is always the most up-to-date version and preventing memory leaks.