Im new to React, can someone tell me why is this happening...?

Viewed 80

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)

1 Answers

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.

Related