JAVASCRIPT
Manage Recurring Actions with useInterval Hook
A custom React hook for setting up and clearing `setInterval` calls, ensuring that recurring actions are handled safely and effectively within your components.
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) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
export default useInterval;
// Example Usage:
// function Timer() {
// const [count, setCount] = useState(0);
// useInterval(() => {
// setCount(count + 1);
// }, 1000); // Update every 1 second
// return <div>Count: {count}</div>;
// }
How it works: The `useInterval` hook provides a robust way to implement recurring actions using `setInterval` in React. It stores the provided callback in a `useRef` to ensure that the interval always calls the latest version of the function without needing to restart the interval itself. The `useEffect` hook manages the `setInterval` and `clearInterval` lifecycle, automatically clearing the interval when the component unmounts or when the `delay` changes.