State in ReactJS

React State
The state is an updatable structure. In a component, change in state over time can happen. The state is used to contain data or information about the component and also take the responsibility to make a component dynamic and interactive. The components that have their own state are known as a stateful component, while the components that don’t have their own state are known as a stateless component.

Methods:
setState() method: It is used to set a state and it also triggers UI updates on calling.
getInitialState(): It is used to set an initial state before any interaction occurs.

Defining State Example:

import React, { Component } from 'react';  
class App extends React.Component {  
constructor() {  
super();  
this.state = {  
data:   
[  {             
"name":"Dhoni"             
},  
{            
"name":"Kohli"             
},  
{    
"name":"Pandya"          
}  ]  
}  
}  
render() {  
return (  
<div>  
<PLAYERname/>  
<ul>            
{this.state.data.map((item) => <List data = {item} />)}           
</ul>  
</div>  
);  
}  
}  
class PLAYERname extends React.Component {  
render() {  
return (  
<div>  
<h1>Player Names</h1>  
</div>  
);  
}  
}  
class List extends React.Component {  
render() {  
return (  
<ul>            
<li>{this.props.data.name}</li>   
</ul>  
);  
}  
}  
export default App;

Output:

Player Names
     ●	Dhoni
     ●	Kohli
     ●	Pandya

Explanation:
To declare a default set of values a class constructor is used. It assigns an initial state using this.state. The render() method renders the ‘this.state’ property. Here we are creating a stateful component using ES6 syntax. The super() method initializes this.state.

Changing the State:
We can also change the component state. For this, we are using the setState() method. We then pass a new state object as the argument.

Example:

import React, { Component } from 'react';  
class App extends React.Component {   
constructor() {  
super();        
this.state = { displayBio: false };  
console.log('Component this', this);  
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);  
}  
toggleDisplayBio(){  
this.setState({displayBio: !this.state.displayBio});  
}  
render() {  
return (  
<div>  
<h1>Hello World</h1>  
{  
this.state.displayBio ? (   
<div>  
<p>Have a Great Day.</p>  
<button onClick={this.toggleDisplayBio}> Less </button>  
</div>  
) : (  
<div>
<button onClick={this.toggleDisplayBio}> More </button>  
</div>  
)}  
</div>  
)  
}  
}  
export default App;

Output 1:
React state 1

Output 2:
React state 2

Please Share