React useInterval hook
Implements setInterval() in a declarative manner.
- Create a custom hook that takes a
callbackand adelay. - Use the
useRef()hook to create areffor the callback function. - Use a
useEffect()hook to remember the latestcallbackwhenever it changes. - Use a
useEffect()hook dependent ondelayto set up the interval and clean up.
const useInterval = (callback, delay) => {
const savedCallback = React.useRef();
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
const tick = () => {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};