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

React | Why add () when using prevState in setState()?

In React when not using preState the code is like:

tick = () => {
        if(this.state.isRunning) {
            const now = Date.now();
            this.setState({
                previousTime: now,
                elapseTime: prevState.elapseTime + (now - prevState.previousTime),
            });
        }
}

My understanding of the codes above is we passed a project with the part of state to update. However when using prevState, we have to add parentheses around the project, as is shown below:

tick = () => {
        if(this.state.isRunning) {
            const now = Date.now();
            this.setState(prevState => ({
                previousTime: now,
                elapseTime: prevState.elapseTime + (now - prevState.previousTime),
            }));
        }
    }

So why we have to add () here? what is the function of them?

1 Answer

Robert Manolis
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Robert Manolis
Treehouse Guest Teacher

Hi Yanhan, great question. When you use prevState, you pass a function to the setState method rather than the usual object. And when you're returning an object without a return keyword, as is the case here with the concise arrow syntax, you need to wrap the object in parens so the interpreter doesn't think the curly braces are defining the function body rather than the object being returned.

Hope that helps, and makes sense. :smiley: