JavaScript React Basics Understanding State Remove Items From State

Truman Smith
Truman Smith
Full Stack JavaScript Techdegree Graduate 17,901 Points

How is score preserved after a player is removed?

I was pleasantly surprised when scores are not reset to 0 after a player is removed and the player list is re-rendered. How? The App component renders the player list using state.players which contains only name and id. Score is stored on the Counter components. How is it that scores are not lost? It appears that the previous Counter and/or Player components are retained when App re-renders.

2 Answers

Dale Severude
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dale Severude
Full Stack JavaScript Techdegree Graduate 71,316 Points

Component state is unaffected by application state. The application state is just an array of players while each component state contains the player name, id, key and a function.

I hope this makes sense. The previous lecture explains about this.

https://teamtreehouse.com/library/creating-the-application-state

Truman Smith
Truman Smith
Full Stack JavaScript Techdegree Graduate 17,901 Points

It's my understanding that render( ) executes when App is first created and after its state changes, which happens when a player is deleted (removed from state.players array). The score is not in App's state, but in Counter's state which is a component in Player. When render( ) executes the state.players.map( ) statement it appears that Player + Counter components and their states are reused rather than recreated.

class App extends React.Component {

  constructor() {
    super()
    this.state = {
      players: [
        { name: "Guil", id: 1 },
        { name: "Treasure", id: 2 },  ...
      ]}
  }

  handleRemovePlayer = (id) => { ... }

  render() {
    return (
      <div className="scoreboard">
         ...
        {/* players list */}
        { this.state.players.map( (player) => {
            return (
              <Player
                name={player.name}
                id={player.id}
                key={player.id.toString()}
                removePlayer={this.handleRemovePlayer}
              />
          )})}
      </div>
    )}}

It smells like magic to me, but perhaps someone has a better explanation.