JAVASCRIPT
Simplified Timers with `useInterval` React Hook
Learn to create a custom `useInterval` React hook for easily setting up and clearing recurring timers, perfect for animations, counters, or polling data.
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]);
}
How it works: The `useInterval` hook simplifies using `setInterval` in React components by handling cleanup automatically. It takes a `callback` function and a `delay`. The `useRef` hook stores the latest `callback` to prevent stale closures, ensuring that the interval always executes the most current version of your function. The `useEffect` then sets up the interval, clearing it when the component unmounts or the `delay` changes, ensuring efficient and bug-free timer management.