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: