react js state

 many of the situation when you want to call something after the set state then you will use callback:--


increment(){

this.setState({

count:this.state.count+1

},()=>

console.log("callback values",this.state.count)

)

}

code:

import React, { Component } from 'react'

export class S1 extends Component {
constructor(props) {
  super(props)

  this.state = {
     count:0
  }
}
increse=()=>{
  
this.setState({
    count:this.state.count+1

},()=>console.log(this.state.count))
//console.log(this.state.count);
}
    render() 
  {
    return (
  
        <div>{this.state.count}
         <button onClick={this.increse}>click</button>
        </div>
       
    )
  }
}

export default S1




incrementFive(){

increment();

increment();

}

all five methods goes in one go....

its normal behavior ...

so:---

this.setState(

(prevState)=>({

count:prevState.count+1

})

)

..............................................................................................

import React, { Component } from 'react'

export class S1 extends Component {
constructor(props) {
  super(props)

  this.state = {
     count:0
  }
}
increse=()=>{
  
this.setState(prevState=>({
    count:prevState.count+1

}),()=>console.log(this.state.count))
//console.log(this.state.count);
}
    render() 
  {
    return (
  
        <div>{this.state.count}
         <button onClick={this.increse}>click</button>
        </div>
       
    )
  }
}

export default S1








.......................................................................................................

this.setState(

(prevState,props)=>({

count:prevState.count+props.

})

)




..............................................................................................................

91

prevState is a name that you have given to the argument passed to setState callback function. What it holds is the value of state before the setState was triggered by React; Since setState does batching, its sometimes important to know what the previous state was when you want to update the new state based on the previous state value.

So if multiple setState calls are updating the same state, batching setState calls may lead to incorrect state being set. Consider an example:

Comments

Popular posts from this blog

interview questions js[ Anurag Singh ProCodrr]

reactnative_creation