0

Shown below is a snippet of the declaration of a function in my react component:

increment() {
    this.setState(state => ({
      count: state.count + 1
    }));
  }

Notice that there is parenthesis right after the arrow. I do not understand why this code wouldn't work without the parenthesis, since it wasn't required in another similar case:

toggleVisibility() {
    this.setState(state => {
      if (state.visibility === true) {
         return { visibility: false };
       } else {
         return { visibility: true };
      }
    });
  }

When do I use the parenthesis?

I'm a new self-learn coder, please be kind on me! Many thanks.

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181
0xNike
  • 15
  • 2
  • 1
    It's nothing specific to setState. [See the advanced syntax for arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#advanced_syntax). In the context of an arrow function, curly brackets might mean an object or they might mean a function body. The syntax of javascript is such that if you want to make it to mean an object, you wrap it in parentheses. – Nicholas Tower Jul 31 '22 at 15:29
  • Does this answer your question? [Arrow functions and the use of parentheses () or {} or ({})](https://stackoverflow.com/questions/49425755/arrow-functions-and-the-use-of-parentheses-or-or) – Henry Woody Jul 31 '22 at 15:29

1 Answers1

1

It's not really a react thing, it's a javascript syntax. Using parenthesis is a shortcut for returning an object.

For example,

const items = [1, 2, 3, 4, 5]

const withParenthesis = items.map((item) => ({item}));

// is the same with
const withoutParenthesis = items.map((item) => {
  return {item};
})

Keep in mind that you need to manually return when not using ({})

Kevin Yobeth
  • 939
  • 1
  • 8
  • 17