Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 11, 2019 09:56
Show Gist options
  • Select an option

  • Save freddi301/68ba463381008ebab119e591ed67fcee to your computer and use it in GitHub Desktop.

Select an option

Save freddi301/68ba463381008ebab119e591ed67fcee to your computer and use it in GitHub Desktop.
useInterval #react #hook
/**
* This is an implementation of javascript's imperative setInterval API
* combined with React hooks' declarative approach.
*
* It is actually a replica of Dan Abramov's implementation described here:
* https://overreacted.io/making-setinterval-declarative-with-react-hooks/
*/
import { useEffect, useRef } from "react";
export function useInterval(callback: any, delay: number | null) {
const savedCallback = useRef<any | null>(null);
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
return;
}, [delay]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment