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

JavaScript

Stephen Pierce
Stephen Pierce
12,047 Points

Where was prevScore defined?

I am struggling to understand where prevScore was defined. Is this a native feature of React where a state is automagically given a prev_ value?

1 Answer

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

Hey Stephen Pierce 👋 Great question. I'm assuming you're talking about this piece of code:

const Counter = () => {
    const [score, setScore] = React.useState(0);

    const incerementScore = () => {
        setScore(prevScore => prevScore +1);
    }
    ...
}

To understand what prevScore is lets first take a look at setScore. setScore is a function that updates the score state. You can pass setScore a value or a function (which is what we're doing here). We are passing setScore an arrow function prevScore => prevScore +1 where prevScore is the parameter the arrow function takes in (since it's just a parameter we can name it what ever we want, I just named it "prevScore"). Behind the scenes React uses this function to know how to update the score state. So it sets prevScore equal to the current value of the score state and sets score to score +1 (in our case above).

I hope this helps! If you want to learn more about useState's set function click this link.

If you want to learn why we can't just pass setScore(score +1) I recommend looking at this forum post

Stephen Pierce
Stephen Pierce
12,047 Points

Thank you, this was very clear!

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

Thanks Laura, this is really well explained :)

I've noticed this pattern of 'automatic' parameters before, but haven't seen the proper term for it; perhaps you can tell me?

For example, in (non-React) event handling, the event object (e) is passed in automatically by the browser -- we just need to give it a variable to access it in the function body.

Hi Laura! So does this mean that react ALWAYS uses the value of the state/score within useState() as the parameter given in the arrow function?