0

This line works as the content after arrow in wrapped in ()

this.setState((prevState) => ({toggle:prevState.toggle + 1}))

The content after arrow is not wrapped in () so it is not working

this.setState((prevState) => {toggle:prevState.toggle + 1})
matthias_h
  • 11,356
  • 9
  • 22
  • 40
Atul
  • 11
  • 3
  • 1
    This is really to do with the JS arrow function, it's not exclusive to React. – DBS Apr 27 '20 at 16:29
  • 1
    Maybe this answers it for you: https://stackoverflow.com/questions/49425755/arrow-functions-and-the-use-of-parentheses-or-or/49425823#49425823 – Shubham Khatri Apr 27 '20 at 16:31

2 Answers2

3

Arrow functions may implicitly return values by simply omitting the curly braces that traditionally wrap a function's body if their body only contains a single expression.

const foo = x => x + 1;
foo(1); // -> 2

When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not mistaken for the opening of the function's body.

const foo = () => { bar: 1 } // foo() returns undefined
const foo = () => ({ bar: 1 }) // foo() returns {bar: 1}
Jagrati
  • 11,474
  • 9
  • 35
  • 56
1

When you want to implicitly return an object, curly braces do not work because they denote start and end of block. In order to distinguish between block and JS object, you wrap the object in ().

gautamits
  • 1,262
  • 9
  • 11