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 Update the Stopwatch State with componentDidMount()

Begana Choi
Begana Choi
Courses Plus Student 13,125 Points

why don't we use prevState in tick function for ( now - this.state.previousTime )?

prevState is the better way to verify that state did update correctly. but why we don't use prevState for this part?

tick = () => {
            const now = Date.now();
            this.setState( prevState => ({
                previousTime: now,
                elapsedTime: prevState.elapsedTime + ( now - this.state.previousTime ) <<this part

1 Answer

Mia Filisch
Mia Filisch
15,381 Points

I was just wondering the same thing! My understanding is that it's always better to use prevState than this.state when updating state based on existing state, so I assume this is simply an oversight. I used prevState in both places and it seems to work fine!