I know this is occurring due to React.StrictMode, but am very confused exactly how this behavior is occurring.
Basically, I have a very simple component, that logs each time it renders, and also increments a global counter when it does so
let logCount = 0;
function App() {
const [count, setCount] = React.useState(0);
const incrementCount = React.useCallback(() => setCount(count + 1), [count]);
console.log(logCount++, Math.random());
return (
<div>
{count}
<button onClick={incrementCount}>rerender me!</button>
</div>
);
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.querySelector("#root")
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
Each time the component rerenders, I will see only a single console.log, but logCount will have incremented twice. If I turn off React.StrictMode, it will only have incremented a single time.
I'm mostly just curious if react has some special logic to ensure console.log statements and the like are only executed a single time, even in strict mode? If not, then I'm even more curious what I'm missing here. I added a Math.random() call as a sanity check.