3

Lets say whe have this state

state = {
  name: 'Daniel',
  fruits: {
    one: 'Banana',
    two: 'Apple'
  }
}

I could update this with

this.setState({
  fruits: {
    ...this.state.fruits,
    one: 'Pineapple'
  }
})

or i could do

this.setState(prevState => ({
  fruits: {
    ...prevState.fruits,
    one: 'Pineapple'
  }
}))

I understand that if you have a counter that should be incremented, it would be a good idea to make sure you're incrementing from the previous state. But if we are changing a name and don't care about the previous name. Is there any benefit of using prevState in that case?

Do you only need to use prevState if you're actually calculating something based on the previous state? In this case, we are spreading the fruits object. Could this object been changed in another call simultaniously and the version without prevState overriding it? (Do i always have to use prevState when handling objects in state?)

Glutch
  • 662
  • 1
  • 6
  • 19
  • Good documentation here https://reactjs.org/docs/react-component.html#setstate and here https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous – Striped Apr 25 '18 at 12:08
  • Keep in mind, setState() is async. Whenever you're calling setState(), it does not mean your state will update immediately. If you're new state is depends on previous state, it is better way to use function expression to get previous state. – Ritwick Dey Apr 25 '18 at 12:10
  • I have read those (and just did again). But i still don't feel like my question is answered. I totally understand the incremental situation. But if we are changing a name inside an object - and we do not care about the previous name. is prevState required? recommended? – Glutch Apr 25 '18 at 12:15
  • Basically, if you need the state to update your current state, use prevState, otherwise juste use the `setState({ key: value })` form. – Striped Apr 25 '18 at 12:17
  • By that you mean that prevState is not required in my two examples? And it could never fail or overwrite something else in the fruits object? – Glutch Apr 25 '18 at 12:20
  • I think the signature `setState(updater, callback?)` is used to be able to write pure functions to update state outside of your components, like: `function(prevState) { return { counter: prevState.counter + 1 } }` Pure functions are more easily tested – Dusan Jovanov Apr 25 '18 at 12:41
  • Simple question. Do i need to use prevState in my example? – Glutch Apr 25 '18 at 12:43

0 Answers0