state in ReactJS

State of component in ReactJS is some object of information that component can have. This information may be changed during the life of the component.

So you can think of State of component as the data that is needed by component. That data can be anything. For example, the Login component can have userName and password as the state object, To-do list component can have a status of completion and task name as the state object.

Use state

You already know that every react component is derived from React.Component ( Component class of react ). So if there is no state for component, it is not mendatory to create constructor because constructor of the base class React.Component will be called on creating the instance of the class. And it will assign null value to the state object of the class.

When you need to add state for the component, you need to initialize it in constructor. You must call super(props) which will call the constructor of the React.Component class and initialize needed things. And after that, initialize state object.
Let us have a look at an example.


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

class Counter extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            clickCount: 0
        };
        this.onButtonClick = this.onButtonClick.bind(this);
    }
    onButtonClick(e){
        const { clickCount } = this.state;
        this.setState({
            clickCount: clickCount + 1
        });
    }
    render(){
        const { clickCount } = this.state;
        return (
            <div>
                <div>Total Count : { clickCount }</div>
                <button onClick={this.onButtonClick}>Increase counter</button>
            </div>
        );
    }
}

ReactDOM.render(
    <Counter />,
    document.getElementById('root')
);
                    

Open above code in codepen.

In above code, we have used this.setState function to set the state variable. We will see it in setState function section.

Conclusion

In this section, we have learned about state in ReactJS.
In the next section, you will learn about setState function in ReactJS.