Created
March 4, 2022 19:35
-
-
Save mhtocs/e6f706b26ec6241a67a6195aecabbfaf to your computer and use it in GitHub Desktop.
A counter in ReactJS
This file contains 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"; | |
const App = () => { | |
const [counter, setCounter] = React.useState(0); | |
return ( | |
<div> | |
<h2>Counter: {counter}</h2> | |
{/* | |
When you set a state based on previous value, it's usually better to use a callback: | |
Setting state is asynchronous. In more complicated cases, weird bugs may occur if you don't use callback method | |
So, instead of setCounter(counter + 1) | |
we do setCounter(counter => counter + 1); | |
*/} | |
<button onClick={() => setCounter((counter) => counter + 1)}> | |
Increment | |
</button> | |
<button onClick={() => setCounter((counter) => counter - 1)}> | |
Decrement | |
</button> | |
</div> | |
); | |
}; | |
ReactDOM.render(<App />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment