Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What is the difference between using constructor vs getInitialState in React?

  • Last Updated : 01 Feb, 2021

The constructor and getInitialState both in React are used to initialize state, but they can’t be used interchangeably. The difference between these two is we should initialize state in the constructor when we are using ES6 classes and define the getInitialState method when we are using React.createClass (ES5 syntax). So the difference between constructor and getInitialState is the difference between ES6 and ES5 itself.

We use getInitialState with React.createClass and constructor is used with React.Component.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax:

class App extends React.Component {
constructor(props) {
  super(props);
  this.state = { /* initial state */ };
}
}

Syntax:



var App = React.createClass({
getInitialState() {
  return { /* initial state */ };
},
});

Both the above syntax to initialize state is equivalent.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Initializing state using constructor:

Javascript




import {React ,Component} from 'react'
class App extends Component{
     
  constructor(props) {
    super(props);
    this.state = {
      username: "kapilchhipa4",
      password: "12345678"
    }
  }
    
  render() {  
    return (
      <div>
      <h3>Username: {this.state.username}</h3>
      <h3>Password: {this.state.password}</h3>
      </div>
      
  }
}
    
    
export default App

Initialize state using getInitialState method:

Note: We need to install a library to use the createReactClass method using the following command:

npm install create-react-class --save

Javascript




import { React } from 'react'
  
var App = React.createClass({
  
  getInitialState() {
    return
      username: 'kapilchhipa4',
      password:'12345678'
    };
  },
  
  render() {
    return (  
      <div>
        <h3>Username: {this.state.username} </h3>
      </div>
    )
  }
});
  
    
    
export default App

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!