I'm going through the "Quick Start" portion of React's website, and it uses code that looks something like this:
toggleClicked() {
this.setState(prev => ({
isOn: !prev.isOn
}));
}
Why do I need the extra parentheses around the function block? I would think that it would look like this:
toggleClicked() {
this.setState(prev => {
isOn: !prev.isOn
});
}
But this doesn't work. What do these parentheses mean?
Always use the setState() method to change the state object, since it will ensure that the component knows it's been updated and calls the render() method.
Because of all the work actually involved when the setState() function is called, React may batch multiple setState() calls into a single update to improve performance. Thanks to this batching process, this. state might be updated asynchronously which means you cannot always rely on the current this.
Syntax: We can use setState() to change the state of the component directly as well as through an arrow function. Example 1: Updating single attribute. We set up our initial state value inside constructor function and create another function updateState() for updating the state.
The second argument that can optionally be passed to setState is a callback function which gets called immediately after the setState is completed and the components get re-rendered.
The interpreter considers the {
after =>
to be the start of a function block, rather than an object - so, wrap it in parentheses to make it clear that you're returning an object there, rather than defining a function.
this.setState(prev => ({
isOn: !prev.isOn
}));
The braces around isOn: !prev.isOn
is the object literal notation.
The parentheses immediately surrounding that is mandatory to indicate that the above braces represent an object literal instead of a function body. This distinction is necessary because the right hand side of a "fat arrow" (=>
) can either be a proper function body (surrounded by braces) or an expression (which is an implicit return
). In the latter case, it's possible for that expression to be an object literal, which will be confusing for the parser (I'm sure the TC 39 committee studied the language grammar and concluded that it's not possible for the parser to distinguish the two use cases without the help of explicit parentheses).
The next outer parentheses are the delimiters of the arguments passed to setState
.
The outer most pair of braces are the delimiters of the function body of toggleClicked
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With