State in ReactJS

State in ReactJS is a built-in object. It is very similar to props, but it is private and fully controlled by the components. You can create state only in the class component. Unlike props, state can be modify.

Whenever the state object changes, the component re-renders.

There are two ways to initialize the state in React Component.

  • Directly inside the Class Component
  • Defining the state in Component Constructor

State Directly inside the Class

Tutorial.js

import React, { Component } from "react";

class Tutorial extends Component{
    state = {
        tutorial_name : "ReactJS"
    }

    render(){
        return <h1>Learn Online {this.state.tutorial_name}</h1>;
    }
}

export default Tutorial;

index.js

import React from "react";
import ReactDOM from "react-dom";

import Tutorial from './Tutorial';

//Rendering component...
ReactDOM.render(<Tutorial />, document.getElementById("root"));

State inside the Class Constructor

Tutorial.js

import React, { Component } from "react";

class Tutorial extends Component{
    constructor(props){
        //It is required to call all parent class constructor...
        super(props);
        this.state = {
            tutorial_name : "ReactJS"
        };
    }

    render(){
        return <h1>Learn Online {this.state.tutorial_name}</h1>;
    }
}

export default Tutorial;

index.js

import React from "react";
import ReactDOM from "react-dom";

import Tutorial from './Tutorial';

//Rendering component...
ReactDOM.render(<Tutorial />, document.getElementById("root"));

Trending Topics