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 React Components Stateful Components and the Effect Hook Stopwatch State

Ben McMahan
Ben McMahan
7,921 Points

prevValue?

<button onClick={() => setIsRunning((prevValue) => !prevValue)}>
                {isRunning ? "Stop" : "Start"}
            </button>

Can someone break down how prevValue is assigned as a Boolean? And why not use isRunning?

1 Answer

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

Hey Ben McMahan Great question! When you pass useState's set function (setIsRunning) a function, React will calculate the next state by applying all of the queued updaters to the previous state. So in other words React applies all the other set functions and then gets the current value of isRunning and sets it to prevValue.

For now we could just use isRunning instead of prevValue because our app is small. Once our app gets bigger and isRunning might be updated in different locations then you should pass a function to setIsRunning. It's best practice to always pass the set function a function when you are updating your state based on it's previous value.

If you want to see the drawback in just passing the state in their set function I recommend taking a look at this forum question. And here's some more resources on useState and their set function.

I hope this cleared some things up!