0

Suppose I have a state,

state = {
  counter: 0
}

On the click of button I want to update the state.

My updateCounter function is this,

updateCounter = () => {
    this.setState({counter: 1})
}

Which work perfectly.

I come across situation where people are using this,

updateCounter = () => {
    this.setState(prevState => ({
       ...prevState,
       counter: prevState.counter + 1
    }))
}

My question's are,

  1. What is the difference between them?

  2. Why we have 2 setState?

  3. Is there any performance gain of using any one?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
RSquare
  • 69
  • 1
  • 7
  • 1
    The second one is only relevant if you have some state other than `counter`, and you'd like to set some new state based on its previous value. – silencedogood Sep 17 '19 at 15:48

2 Answers2

1

The second variation exists so that you can calculate the new state based on the old state. If that's something you need to do, you should use the second one, or you can have subtle bugs where you don't set the state to the value you were expecting. If your new state is unrelated to the previous state, then it doesn't matter which one you use.

P.s, spreading the previous state is unnecessary in this code. In class components's this.setState React will do a shallow merge for you:

this.setState(prevState => ({
   ...prevState, // <-- not needed
   counter: prevState.counter + 1
}))
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • 1
    It's more than that, specifically, if the state is set more than once within an update cycle, use the first way if you always want the same output regardless of the number of times it was called, or the second one to compute the total value with each call. – Emile Bergeron Sep 17 '19 at 15:50
0

setState method has two forms:

  • the one where you just pass it a new value to set to the state (your first example).
  • the functional form, where you use the value of the current state to set your new state (your second example).

So for example, in case with a counter, if you're incrementing the counter from a state by 1, it's better to use the functional form of setState, because it makes sure that you're using the most current value from the state.

Additionally, not using the functional form in case where your new state depends on the current state may lead to some bugs. I wrote a bit more in detail about it and other common issues earlier.

It's also nicely explained in the official React documentation.

Clarity
  • 10,730
  • 2
  • 25
  • 35