Created
June 26, 2019 02:23
-
-
Save jeiea/b03107955a1f50524a982cab684ac30e to your computer and use it in GitHub Desktop.
React hook version of useInterval
This file contains hidden or 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
import { useEffect, useState } from 'react'; | |
function useInterval(interval, setter) { | |
const [updater] = useState({}); | |
updater.update = setter; | |
useEffect(() => { | |
const id = setInterval(() => { | |
updater.update(c => c + 1); | |
}, interval); | |
return () => clearInterval(id); | |
}, [interval, updater]); | |
} | |
const App = props => { | |
const [count, setCount] = useState(0); | |
const [int, setInt] = useState(1000); | |
useInterval(int, () => setCount(c => c + 1)); | |
useEffect(() => { | |
if (count > 10 && int > 200) { | |
setCount(0); | |
setInt(int / 2); | |
} | |
}, [int, count]); | |
return (<div style={{ width: '400px', height: '500px' }}> | |
<p>Count: {count}</p> | |
</div>); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment