State

State helps us to hold the current app state there are even separate libraries to manage the state in react most popular library is redux.

we can use state in only class Based components.

In below example, we are using the single stateful component which is holding the all our app state by using props we are passing the data to stateless Name component

function Name(props){
    return <h1>{props.myname}</h1>
}

class App extends React. Component{
    constructor(props){
        super(props);
        this.state={name:"React"}
    }
    render(){
        return(<div>
          <Name  myname={this.state.name} />
        </div>)
    }
}

final dom looks like

<div>
<h1>React</h1>
</div>

In react we cannot mutate the state directly.

this.state.name = "king" //not possible in react

There is only one way to mutate the state in react is by using the setState method. setState doesn’t guarantee you to update the state immediately.

Like in below example this.state.num property is updating every time when we click an Increment button.

setState method

class Counter extends React.Component{
  constructor(props){
      super(props);
      this.state ={num:0}
  }

 onIncrement(){
     this.setState({num:this.state.num+1});
 }

 render(){
     return (
         <div>
         <h2>{this.state.num}</h2>
         <button onClick={this.onIncrement.bind(this)}>Increment</button>
         </div>
     )
 }

}

class Counter extends React.Component{
 constructor(props){
 super(props);
 this.state ={num:0}
 }
onIncrement(){
 this.setState({num:this.state.num+1});
 }
render(){
 return (
 <div>
 <h2>{this.state.num}</h2>
 <button onClick={this.onIncrement.bind(this)}>Inc</button>
 </div>
 ) }
}

Output

0