Reputation: 315
I have the following code:
// App.js
import { useEffect } from "react";
let count1 = 0;
function App() {
console.log("render");
console.log("before", count1);
count1 += 1;
useEffect(() => console.log("effect", count1));
console.log("after", count1);
return <button></button>;
}
export default App;
// index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
rootElement
);
After initial rendering, The console result in Chrome is:
I don't know why the value of count1
is 2
at last.
Upvotes: 2
Views: 43
Reputation: 2968
It is because of the StrictMode
wrapper that has been used in your index.js
probably.
You can read about it here in the doc.
This is a feature provided for developers to diagnose bugs more easily, and as it's been said in the doc:
Strict mode checks are run in development mode only; they do not impact the production build.
If you do not like this feature, you can remove it from your projects and as you can see here in sandbox, it's rendering once now after I commented Strictmode.
Upvotes: 2