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 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
STAFF
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: