zzz6519003 / blog

My blog about coding
4 stars 1 forks source link

Functional setState is the future of React(1) #77

Open zzz6519003 opened 7 years ago

zzz6519003 commented 7 years ago

Functional setState is the future of React(1)

https://medium.freecodecamp.com/functional-setstate-is-the-future-of-react-374f30401b6b#.53jfkymr8

setState() also accepts a function. The function accepts the previous state and current props of the component which it uses to calculate and return the next state.

this.setState(function (state, props) {
 return {
  score: state.score - 1
 }
});

Why pass a function to setState?

The thing is, state updates may be asynchronous.

what happens when setState() is called: React will first merge the object you passed to setState() into the current state. Then it will start that reconciliation thing. It will create a new React Element tree (an object representation of your UI), diff the new tree against the old tree, figure out what has changed based on the object you passed to setState() , then finally update the DOM.