2

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:

enter image description here

I don't know why the value of count1 is 2 at last.

1
  • It is because you use the Hook useEffect. And this by default runs both after the first render and after every update. Commented Mar 25, 2021 at 9:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.