Created
February 7, 2019 07:48
-
-
Save SanichKotikov/020ccebd9e5c4cafe7162907d56a422d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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