Skip to content

Instantly share code, notes, and snippets.

@azamatsmith
Last active March 2, 2019 00:56
Show Gist options
  • Save azamatsmith/9e132b3b666fbd15bc6a4a8e49fda11a to your computer and use it in GitHub Desktop.
Save azamatsmith/9e132b3b666fbd15bc6a4a8e49fda11a to your computer and use it in GitHub Desktop.
React Hooks - Timer example using setInterval
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