Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Last active February 19, 2019 17:25
Show Gist options
  • Save DroopyTersen/5fed190114d7a894126b2cac4778cc4e to your computer and use it in GitHub Desktop.
Save DroopyTersen/5fed190114d7a894126b2cac4778cc4e to your computer and use it in GitHub Desktop.
Composing Behavior with React hooks - useInterval
import { useRef, useEffect } from "react";
export default function useInterval(callback, delay) {
const savedCallback = useRef(null);
useEffect(() => {
savedCallback.current = callback;
});
useEffect(
() => {
function handler() {
savedCallback.current();
}
let intervalId = null;
if (delay > 0) {
intervalId = setInterval(handler, delay);
}
return () => {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
};
},
[delay]
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment