4

I have created a react project and added constructor and render menthod to it, while running it I was expecting both constructor and render run once only, but both are running twice. First constructor is running twice and then render. Can someone please help, same was happening to other life cycle methods with me.


import React, {Component} from 'react';
class App extends Component {
  constructor(props) {
    super(props)
    console.log('Constructor')
  }

  render() {
    console.log('render')
    return (
      <h1>My Favorite Color is </h1>
    );
  }
}
export default App;

Here is my index.js.. for how it is called


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

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

<code>This is my output</code>

Manoj
  • 2,059
  • 3
  • 12
  • 24

3 Answers3

8

It works for me, if I replace below code

ReactDOM.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
    document.getElementById('root')
  )

by below line (but the above code is the one I got as default code on creating a project using create-react-app command.

ReactDOM.render(<App />, document.getElementById('root'));
Manoj
  • 2,059
  • 3
  • 12
  • 24
4

I had the same problem and just removed React.StrictMode and now everything renders only once.

2

Actually this is the intended behavior of StrictMode as documented in the React Docs. It is explained in the docs that React has two phases, namely render and commit. In the future, Concurrent Mode will try to avoid blocking the browser thread by stopping and replaying some lifecycle functions like render, constructor, and more. Strict mode has this feature and it replays these lifecycle methods.

React Docs also say that these lifecycle functions should NOT contain any side-effects. Having side effects will cause memory leaks and invalid application state.

My personal opinion is that you should keep all the side-effects to safe lifecycle functions as described in the docs. Link to the specific section of the docs that explain this.

Mehmet Efe Akça
  • 1,132
  • 10
  • 9