Created
February 6, 2019 13:13
-
-
Save gisderdube/4cf3d02eb91f28fb6b9b517cfa8f8c39 to your computer and use it in GitHub Desktop.
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 React, { useEffect, useState, useRef } from 'react' | |
| function useInterval(callback, delay) { | |
| const savedCallback = useRef() | |
| useEffect(() => { | |
| savedCallback.current = callback | |
| }) | |
| useEffect(() => { | |
| function tick() { | |
| savedCallback.current() | |
| } | |
| if (delay !== null) { | |
| let id = setInterval(tick, delay) | |
| return () => clearInterval(id) | |
| } | |
| }, [delay]) | |
| } | |
| function Counter() { | |
| const [count, setCount] = useState(0) | |
| useInterval(() => { | |
| setCount(count + 1) | |
| }, 1000) | |
| return ( | |
| <div> | |
| Current count is: {count} | |
| <br /> | |
| <button onClick={() => setCount(count + 1)}>Increase count</button> | |
| </div> | |
| ) | |
| } | |
| export default Counter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment