React - Render Conditionally from Props

General question, why is the “prevState” parameter there?

Their code:

handleClick() {
    this.setState(prevState => {
      // Complete the return statement:
      return {
        counter: prevState
      }
    });

My code:

handleClick() {
    this.setState(prevState => {
      // Complete the return statement:
      return {
        counter: this.state.counter+1
      }
    });

I removed everything not relevant from the code, strictly asking about the prevState parameter inside the this.setState function.
As you can see, I didn’t use the “prevState” and the code worked.
When I went to see their answers, they’ve removed the prevState entirely from the code.

handleClick() {
    this.setState({
      counter: this.state.counter + 1 // change code here
    });
  }

Is this outdated and they just forgot to remove it from the exercise, or am I supposed to use it somehow I’m missing?

Thanks

Challenge: React - Render Conditionally from Props

Link to the challenge:

Arrow functions can be abbreviated depending on the information available. prevState and this.state.counter + 1 effectively do the same thing hence “the code worked”.

This article might also help explain the situation.

Understanding PrevState in React

I hope this helps.

Happy coding: :slightly_smiling_face:

1 Like

It was taught in this challenge

The legacy react docs have some info as well.


Why it is used in the seed code but not the solution is probably just some inconsistency. Either the seed code should not have it, or the solution code should. Otherwise, it just creates confusion. It works both ways but it is still inconsistent the way it was presented.

I updated the solution to use the seed code as that is easier than changing the seed code.

1 Like