Skip to content

Instantly share code, notes, and snippets.

@cyberinferno
Created September 26, 2020 17:24
Show Gist options
  • Save cyberinferno/315adedd243cc4b8ddaae7685cc00db6 to your computer and use it in GitHub Desktop.
Save cyberinferno/315adedd243cc4b8ddaae7685cc00db6 to your computer and use it in GitHub Desktop.
/**
* set interval react hook
*/
import React, { useState, useEffect, useRef } from 'react';
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
});
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment