Skip to content

Instantly share code, notes, and snippets.

@qborreda
Created June 6, 2019 15:16
Show Gist options
  • Save qborreda/ecddece84d8f83842e2d96c528ccc80b to your computer and use it in GitHub Desktop.
Save qborreda/ecddece84d8f83842e2d96c528ccc80b to your computer and use it in GitHub Desktop.
useInterval custom hook
/**
* React custom hook to fire a function given an interval
* @usage: useInterval(()=>{...},1000);
**/
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
});
useEffect(
() => {
function tick() {
savedCallback.current();
}
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