This Setstate

Your app is just a big ball of state.

Two important things to remember…

this.state is just an object that we update for our component
this.setState is a method will call to tell React to update the render(). Nothing magic here. There's not polling or anything.

Whenever we want to update state in our application we have to use setState. In React all you have to do is worry about managing State!

this.setState({
   highlight : !this.state.highlight
}); // Aha! React sees the setState has been called and updates the render()

When state is updated React automatically does a re-render. Woop.
So in essence all we need to do on our container object is update the this.state object with setState.

Good and Bad Examples on when to use setState and functional setState

Good

Functional setState does not wait and updates the value straight away. React uses object merge is you have multiple setStates and submits them at the end. Functional updates the object straight way.

this.setState((prevState, props) => ({
      count: prevState.count + 1
})); // React Submits straight away
this.setState((prevState, props) => ({
      count: prevState.count + 1
})); // React Submits straight away
 
// count = 2;

Bad

incrementCount(){
    this.setState({count : this.state.count + 1}) 
    this.setState({count : this.state.count + 1}) // React waits and only increments by one
  }
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License