JAVASCRIPT
Execute Code Periodically with useInterval Hook
A custom React hook that reliably runs a callback function at a specified interval, with automatic cleanup, perfect for timers or periodic data fetching.
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]); // Only re-run if delay changes
}
export default useInterval;
// Example Usage:
// import React, { useState } from 'react';
// import useInterval from './useInterval';
//
// function Counter() {
// const [count, setCount] = useState(0);
// const [delay, setDelay] = useState(1000);
// const [isRunning, setIsRunning] = useState(true);
//
// useInterval(() => {
// setCount(prevCount => prevCount + 1);
// }, isRunning ? delay : null); // Pass null to stop the interval
//
// const handleDelayChange = (e) => setDelay(Number(e.target.value));
//
// return (
// <div>
// <p>Count: {count}</p>
// <p>Delay: {delay} ms</p>
// <button onClick={() => setIsRunning(!isRunning)}>
// {isRunning ? 'Stop' : 'Start'} Counter
// </button>
// <input
// type="range"
// min="100"
// max="5000"
// value={delay}
// onChange={handleDelayChange}
// />
// </div>
// );
// }
// export default Counter;
How it works: The `useInterval` hook provides a clean way to repeatedly execute a function at a specified time interval, similar to `setInterval`, but with automatic cleanup when the component unmounts or the `delay` changes. It uses `useRef` to maintain a stable reference to the latest callback function and `useEffect` to manage the `setInterval` and `clearInterval` lifecycle. Passing `null` as the `delay` value allows you to conditionally stop the interval.