Skip to content

Instantly share code, notes, and snippets.

@mhtocs
Created March 4, 2022 19:35
Show Gist options
  • Save mhtocs/e6f706b26ec6241a67a6195aecabbfaf to your computer and use it in GitHub Desktop.
Save mhtocs/e6f706b26ec6241a67a6195aecabbfaf to your computer and use it in GitHub Desktop.
A counter in ReactJS
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