Created
January 24, 2023 07:17
-
-
Save p0rsche/1daedd4db772794364407b23342b110f to your computer and use it in GitHub Desktop.
React counter application
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"; | |
import ReactDOM from "react-dom"; | |
// counter app | |
function App() { | |
const [counter, setCounter] = React.useState(0); | |
const [working, setWorking] = React.useState(false); | |
React.useEffect(() => { | |
if (!working) return; | |
const timer = setTimeout(() => { | |
setCounter(counter + 1); | |
}, 1000); | |
return function cleanup() { | |
clearTimeout(timer); | |
}; | |
}, [working, counter]); //using timeouts instead of intervals - setTimeout calls setting counter, which raises useEffect to run again and again in an infinite loop until you stop the timer | |
return ( | |
<> | |
<h4>Counter</h4> | |
<p>{counter}</p> | |
<button onClick={() => setWorking(!working)}> | |
{working ? "Stop timer" : "Start timer"} | |
</button> | |
<button | |
onClick={() => { | |
setWorking(false); | |
setCounter(0); | |
}} | |
> | |
{"Reset timer"} | |
</button> | |
</> | |
); | |
} | |
ReactDOM.render(<App />, document.getElementById("app")); //choose yours |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment