setState

Can Be Tricky

Objectives

  • Use a function as the first parameter to setState

  • Add a callback to setState to determine when the state is up to date

setState That Depends on Previous State

this.state = { counter: 1 };
this.setState({
  counter: this.state.counter + 1
});
this.setState({
  counter: this.state.counter + 1
});
Object.assign({},
  {counter: this.state.counter + 1},
  {counter: this.state.counter + 1},
  {counter: this.state.counter + 1},
);
this.setState({
  counter: this.state.counter + 1
});

setState is Asychronous

this.setState((prevState, props) => {
  return {
    counter: prevState.counter + 1
  };
});

Solution: Update Function

Rule: When a setState depends on previous

          state, use a function parameter

this.setState({name: "Tim"});
// Won't be updated yet
console.log(this.state.name);

setState is Asynchronous

this.setState({name: "Tim"}, () => {
  console.log(
    "Now state is up to date",
    this.state.name
  );  
});