2

This is the code

import React from "react"

let x = 0;

const App = () => {
  x++;
  console.log(x)

  return(
    <div>
      <p>{x}</p>
    </div>
  )
}

export default App;

The console shows 1...but the page shows 2...

How is possible that the code inside the function executes twice(Apparently the x++ runs twice) and the console only outputs one time (1)

  • 2
    Not sure exactly why this is happening, but as a general rule only use `state` properties in your react components. – Shmili Breuer Jan 28 '21 at 20:56
  • 1
    I'm unable to reproduce this, I get 1 in both places. Are you sure this is exactly the code you're running? – twhb Jan 28 '21 at 20:57
  • I don't see any problem here, you may want to try it again as something else is making this happen for sure – Kaustubh Jan 28 '21 at 20:59

1 Answers1

5

This might be caused by rendering your app in React.StrictMode, it causes dual-renders in development mode. https://reactjs.org/docs/strict-mode.html. It also suppresses console calls on subsequent renders, which may explain the difference you're seeing:

Starting with React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions. However, it may cause undesired behavior in certain cases where a workaround can be used.

emeraldsanto
  • 4,330
  • 1
  • 12
  • 25