JAVASCRIPT
React useInterval Hook for Self-Cleaning Timers
Create a custom `useInterval` React hook to easily manage `setInterval` functionality, ensuring proper cleanup and preventing memory leaks in 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) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
// Example Usage:
/*
import React, { useState } => from 'react';
import useInterval from './useInterval'; // Assuming useInterval is in its own file
function Timer() {
const [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000); // Increment every 1 second
return <h1>Count: {count}</h1>;
}
*/
How it works: The `useInterval` hook elegantly manages `setInterval` for React components. It uses `useRef` to store the latest `callback` function, ensuring that the interval always calls the most up-to-date version of the callback without needing to restart the interval itself. The main `useEffect` sets up the `setInterval` only when `delay` is not `null`, and crucially returns a cleanup function that calls `clearInterval`, preventing memory leaks when the component unmounts or the `delay` changes.