Last active
April 8, 2021 02:58
-
-
Save arimariojesus/817e9f27384e6857b71b194b091895d7 to your computer and use it in GitHub Desktop.
setInterval declarative - custom hook
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
import { useEffect, useRef, useState } from 'react'; | |
const useMyHook = (cb, delay = 1000) => { | |
const savedCb = useRef(); | |
useEffect(() => { | |
savedCb.current = cb; | |
}, [cb]); | |
useEffect(() => { | |
const interval = setInterval(() => { | |
savedCb.current(); | |
console.log(delay); | |
}, delay); | |
return () => clearInterval(interval); | |
}, [delay]); | |
}; | |
function App() { | |
const [counter, setCounter] = useState(0); | |
const [delay, setDelay] = useState(1000); | |
const [incrementor, setIncrementor] = useState(1000); | |
useMyHook(() => setCounter((c) => Number(c + 1)), delay); | |
return ( | |
<div> | |
<h1>Counter: {counter}</h1> | |
<h4>Delay: {delay}</h4> | |
<button | |
onClick={() => { | |
setDelay((d) => d + incrementor); | |
}} | |
> | |
+{incrementor} | |
</button> | |
<button | |
onClick={() => { | |
setDelay((d) => d - incrementor); | |
}} | |
> | |
-{incrementor} | |
</button> | |
<input | |
type="number" | |
value={incrementor} | |
onChange={(e) => setIncrementor(Number(e.target.value))} | |
/> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment