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 (2018) Stateful Components and Lifecycle Methods Stopwatch State

Chris Holder
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Holder
Full Stack JavaScript Techdegree Graduate 19,841 Points

Why don't we mutate prevState instead of this.state when we change the value of isRunning?

I thought we weren't supposed to mutate this.state with setState because React sometimes batches state changes and so we should pass a function with prevState to setState instead?

1 Answer

Gabbie Metheny
Gabbie Metheny
33,778 Points

It looks like the React docs recommend setting state using a callback and the previous state, but they do mention you can do it the way Guil has here, too (as a "shallow merge of stateChange into the new state")-- and looking back, we're using the same method of setting state with an object (as opposed to a callback) in AddPlayerForm. It seems like generally, for simpler, smaller state updates (i.e. just change one value, as opposed to updating a large array), this shallow merge approach is sufficient because you're unlikely to get out of sync with the UI. You certainly could refactor this to use a callback, though!

*** EDIT ***

In the next video, we end up adding the callback to update based on prevState as we add more functionality to the Stopwatch!