In setState() why we have to use () before curly brackets {} in arrow function?

Tell us what’s happening:
I’m learning react from last 3 weeks, freecodecamp react curriculam is so awesome.
But some syntax of react is really confusing for beginner. Can anyone help me with it?

  • List item

Your code so far

this.setState(state => ({
counter: state.counter + 1
this.setState((state, props) => ({
counter: state.counter + props.increment

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.

Challenge: Use State to Toggle an Element

Link to the challenge:

In functions, you put the body of the function in curly brackets and you return something

function example() {
  return { name: "Dan" };

Arrow functions are the same:

const example = () => {
  return { name: "Dan" };

But if the body of the arrow function is just a single expression, you can drop the return:

const add = (x, y) => x + y;

But if the thing you’re returning is an object, objects also use curly brackets, so this is ambiguous:

const example = () => { name: "Dan" };

That evaluates to:

const example = () => {
  return name: "Dan";

You need to wrap the result in brackets for that to work:

const example = () => ({ name: "Dan" });

That now evaluates to:

const example = () => {
  return ({ name: "Dan" });

Which is correct

1 Like

but why we are wrapping the function body with first bracket ?

Sorry, pressed reply before I’d finished the answer!