Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

React

why is setPlayers used and prevplayers

const [players, setPlayers] = React.useState([
    {
      name: "Guil",
      score:0,
      id: 1
    },
    {
      name: "Treasure",
      score:0,
      id: 2
    },
    {
      name: "Ashley",
      score:0,
      id: 3
    },
    {
      name: "James",
      score:0,
      id: 4
    }
  ]); 
  const handleScoreChange = (id,delta) => {
    setPlayers(prevPlayers => prevPlayers.map( player => {
      if (player.id === id){
        return{
          name:player.name,
          score:player.score + delta,
          id:player.id
        }
      }
    }));

  }

how is setPlayers a function?is it being passed a prop or another function as a prop?

where did they get prevPlayers?

2 Answers

Travis Alstrand
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Travis Alstrand
Treehouse Teacher

Hi there Ericka Erickson ! :wave:

setPlayers is the function defined at the very top of the code you've added here. It is our way of updating our players state.

prevPlayers (or prevState) is a mechanism to access the state of a component before its latest update, ensuring reliable and consistent state transitions especially in scenarios where the new state depends on the old state. It's not something passed down as props or anything, it's a built-in functionality provided by React and the useState hook.

I hope this makes sense!

thanks that definitely helps!