JAVASCRIPT
Creating a Declarative setInterval with useInterval Hook
Implement a custom useInterval React hook to easily manage recurring actions with automatic cleanup, preventing common setInterval issues and memory leaks.
import React, { 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 Counter() {
const [count, setCount] = React.useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000); // Update every 1 second
return <h1>{count}</h1>;
}
export default Counter;
How it works: The `useInterval` hook allows you to use `setInterval` declaratively in your React components. It takes a callback function and a delay in milliseconds. It uses `useRef` to keep a stable reference to the latest callback function, ensuring that the interval always calls the most up-to-date version without needing to restart the interval itself. The `useEffect` hook handles setting up and clearing the interval, automatically cleaning up when the component unmounts or the delay changes, preventing memory leaks.