I tried to track the number of times react component is rendered. However, it seems that the renderCounter gets incremented by 2 each time.
Why does this happen? I know it is a bad practice to use global variables, but I'm interested in the reason why this happens.
https://codesandbox.io/s/rendercounter-does-not-increment-correctly-093ok?file=/src/App.js
let renderCounter = 1;
function App() {
const [i, inc] = useReducer((_) => _ + 1, 1);
// render
console.log(JSON.stringify(i), "th click");
console.log("renderCounter", JSON.stringify(renderCounter));
renderCounter = renderCounter + 1;
return (
<div>
<button onClick={inc}>increment</button>
</div>
);
}
export default App;