0

In react arrow function return body is wrapped with parenthesis

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

but in the normal function, we wrapped return body with curly brases

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

Can anyone tell me what is the difference between the two return body of function

  • See the linked question's answers. The first one returns an object, which `setState` will use to update state. The second one doesn't specify a return value, so effectively returns `undefined`, and so will be ignored by `setState`. (In the second one, `count:` is a label, not the first part of a property initializer.) – T.J. Crowder Dec 29 '18 at 17:13
  • First of all two functions are not equal. Second one has logic error, it has no return argument. It should be written as `this.setState((state)=>{ return { count:state.count+1 }; })`. Arrow functions can have either a "concise body" or the usual "block body". In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement. – snnsnn Dec 29 '18 at 17:56

1 Answers1

0

The second notation is the classic notation to declare an arroz function with a body. By the way, the snippet has to be modified as it won't work as it is. Here is the working equivalent:

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

An object is created and returned by the function.

The first notation is used for convenience when the value you want to return is straight forward to compute.

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

The parentheses around the returned object are necessary to indicate that the following curly bracies define an object instead of the body of the function.

Baboo
  • 4,008
  • 3
  • 18
  • 33