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 (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!