Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

79
Views
React console.log runs once in render, but side effect occurs twice? StrictMode?

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.

7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.