Skip to content

Instantly share code, notes, and snippets.

@p0rsche
Created January 24, 2023 07:17
Show Gist options
  • Save p0rsche/1daedd4db772794364407b23342b110f to your computer and use it in GitHub Desktop.
Save p0rsche/1daedd4db772794364407b23342b110f to your computer and use it in GitHub Desktop.
React counter application
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