I'm a newbie on frontend development and learning React. Now I'm trying to build a hello-world project.
After executing npx create-react-app myapp, I got an initial React project and I just coded in the file App.js.
import React, {useState} from 'react';
var counter = 0;
function App() {
const [counter2, setCount] = useState(0);
const increment = () => {
setCount(counter2 + 1);
};
return(
<div>
<button onClick= {increment}>Increment</button>
<h1>{counter++}</h1> // 1, 3, 5, 7... WHY???
<h1>{counter2}</h1> // 0, 1, 2, 3...
</div>
);
}
export default App;
After executing npm start, I got my index page, which contains three parts: a button and two numbers.
To my surprise, when I click the button, counter2 is increased as expected, but counter is increased twice. Meaning that keeping clicking the button gives me the result as below:
1 0, 3 1, 5 2...
Why is the global variable counter increased two by two, instead of one by one?
Furthermore, what is the difference between React State and common global variable?