Search code examples
reactjsstaterendering

Why is App.js rendering twice on startup when I run my code in react?


I have started a new React app, with the basic setup of index.js and App.js as starting points.

At the start of my App.js file, I am invoking a console.count() function to count the number of times the App component renders.

Even though App.js is invoked only once in index.js, the console.count() function runs twice, which I interpret as App having rendered twice on startup.

My question is, why is it rendering twice?

Below is App.js

import './App.css';


function App() {
  console.count('App.js rendering');

  return (
    <div>

    </div>
  );
}

export default App;

Below is index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();


Solution

  • That is happening because you are using strict mode. Main idea behind React strict mode is to make finding bugs in your code easier. Check out documentation: https://beta.reactjs.org/reference/react/StrictMode

    Also check out this question: Why is my React component is rendering twice?