Search code examples
javascriptreactjssetstate

How is React updating his state?


I have a question concerning React and how state must be updated. Let's say we have a class Players containing in its state an array of objects called players. We want to update one player in this array. I would have done it this way:

class Players extends Component {

  state = {
      players: []
  }

  updatePlayer = id => {
      const players = this.state.players.map(player => {
        player.updated = player.id === id ? true:false;
        return player
      });
      this.setState({players: players});
  }
}

But my coworker just did it this way, and it's also working:

updatePlayer = id => {
    const playerObj = this.state.players.find(item => {
      return item.id === id
    })

    if (playerObj) {
      playerObj.updated = true

      this.setState({ playerObj })
    }
}

React's function setState update the players array without telling explicitly to do it. So, I have two questions:

  • Is it using a reference from the find function, and using it to update the players arrays ?
  • Is one of those ways recommended ?

Thank you all for your explanations !


Solution

  • The difference is that second snippet misuses setState to trigger an update because it uses playerObj dummy property. This could be achieved with forceUpdate.

    Neither of these ways are correct. Immutable state is promoted in React as a convention. Mutating existing state may result in incorrect behaviour in components that expect a state to be immutable. They mutate existing player object, and new player.update value will be used everywhere where this object is used, even if this is undesirable.

    An idiomatic way to do this is to use immutable objects in state:

    updatePlayer = id => {
      this.setState(({ players }) => ({
        players: players.map(player => ({
          ...player,
          updated: player.id === id
        }));
      });
    }
    

    Notice that setState is asynchronous, updater function has to be used to avoid possible race conditions.