Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

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
Last Updated : 01 Feb, 2021
Like Article
Save Article
Similar Reads
Related Tutorials