Skip to content

Instantly share code, notes, and snippets.

@jeiea
Created June 26, 2019 02:23
Show Gist options
  • Save jeiea/b03107955a1f50524a982cab684ac30e to your computer and use it in GitHub Desktop.
Save jeiea/b03107955a1f50524a982cab684ac30e to your computer and use it in GitHub Desktop.
React hook version of useInterval
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