Skip to content

Instantly share code, notes, and snippets.

@SanichKotikov
Created February 7, 2019 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SanichKotikov/020ccebd9e5c4cafe7162907d56a422d to your computer and use it in GitHub Desktop.
Save SanichKotikov/020ccebd9e5c4cafe7162907d56a422d to your computer and use it in GitHub Desktop.
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
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