Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Components Stateful Components and the Effect Hook Stopwatch State

Ben McMahan
Ben McMahan
7,838 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!