Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor and render methods run twice in react component

Tags:

reactjs

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>

like image 719
Manoj Avatar asked Dec 18 '22 13:12

Manoj


2 Answers

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'));
like image 106
Manoj Avatar answered May 28 '23 07:05

Manoj


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

like image 33
Unanimous 85 Avatar answered May 28 '23 09:05

Unanimous 85