Wednesday, July 3, 2024
HomeLanguagesJavascriptWhat is the difference between using constructor vs getInitialState in React?

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

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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments