Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Functional setState (previous state) different from new updated value?

I'm currently trying to learn React by multiple recent courses.

To update an state, most courses suggest going this way:

 const updatedNinjas = [...this.state.ninjas, newNinja];

    this.setState({
      ninjas: updatedNinjas
    });

However, since setState is "asynchronous", the official react documentation recommends to use the previous state and update based on this one.

this.setState(prevState => ({
      ninjas: [...prevState.ninjas, newNinja]
    }));

Are both solving the same issue (since we use a new array each time in the first example) or is only the last one foolproof?

like image 580
Tanckom Avatar asked Nov 08 '18 08:11

Tanckom


1 Answers

If your new state is calculated based on any value which is already in state - then you should use the second form of setState where you use a function:

this.setState(prevState => ({
  ninjas: [...prevState.ninjas, newNinja]
}));

or even:

this.setState(({ninjas}) => ({
  ninjas: [...ninjas, newNinja]
}));

It's due to state changes are asynchronous and could be batched due to performance reasons.

If you change the state using some variable which is not based on any value from state - you're free to use a simple version:

this.setState({
  answer: 42
});

Regarding your

since we use a new array each time in the first example

indeed you create a new array each time, but you create it using some set of items which can be not relevant by that time when actual state change will be performed by React under the hood.

like image 66
falinsky Avatar answered Oct 15 '22 03:10

falinsky