Chuan
Chuan

Reputation: 469

React, increment global variable does not work as expected

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;

Upvotes: 2

Views: 542

Answers (1)

Nikita Chayka
Nikita Chayka

Reputation: 2137

Yes, react render will be executed twice for you. Why - because your App wrapped in React.StrictMode component in index.js by default, why/what - there are plenty of resources covered it already, so let me just mention this one for example- https://medium.com/@andreasheissenberger/react-components-render-twice-any-way-to-fix-this-91cf23961625 But let me mention right away here - it will not happen if you build in production mode


UPDATE

Now it got really interesting, and i kind of disliked what React developers did. So all of above is valid, yeah, BUT as comment to this post suggested - why then we don't see console.log messages 2 times? WELL because of this - https://github.com/facebook/react/pull/18547 React developers simply disabled console log for second render time. So to see actual behaviour (which should log 2 times each time) you need to kind of play with console log, what i did - wrapped it in setTimeout:

setTimeout(() => console.log(...))

Upvotes: 2

Related Questions