Last active
March 2, 2019 00:56
-
-
Save azamatsmith/9e132b3b666fbd15bc6a4a8e49fda11a to your computer and use it in GitHub Desktop.
React Hooks - Timer example using setInterval
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 from 'react'; | |
function Timer() { | |
const [time, setTime] = React.useState(0); | |
const [timerRunning, setTimerRunning] = React.useState(0); | |
const intervalRef = React.useRef(); | |
React.useEffect(() => { | |
if (timerRunning) { | |
intervalRef.current = setInterval(() => { | |
setTime(prevTime => prevTime + 100); | |
}, 100); | |
} | |
return () => clearInterval(intervalRef.current); | |
}, [timerRunning]); | |
function play() { | |
setTimerRunning(true); | |
} | |
function pause() { | |
setTimerRunning(false); | |
} | |
function clear() { | |
setTime(0); | |
} | |
return {time, play, pause, clear}; | |
} | |
export default Timer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment