React, increment global variable does not work as expected

落爺英雄遲暮 提交于 2021-02-11 07:10:18

问题


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;


回答1:


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(...))


来源:https://stackoverflow.com/questions/64671182/react-increment-global-variable-does-not-work-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!