1

I am having code from youtube tutorial, and i can not figure out why do we need parentheses(commented line), and if anyone can explain in simple way this code... thanks

  const [{count, count2}, setCount] = useState({count: 10, count2: 20})

  return (
    <div className="App">
      <button onClick={ () => 
        setCount(
          currentState => (//can not understand
            {...currentState, count: currentState.count+1}
          )
        )}>+</button>
      <h5>Count 1: {count}</h5>
      <h5>Count2: {count2}</h5>
    </div>
  )
Edy
  • 56
  • 1
  • 9

2 Answers2

4

This has nothing to do with the spread operator.

The => of an arrow function can be followed by either:

  • An expression
  • A block

Since, in JavaScript, a { can start a block or an object initializer (which depends on context), anywhere you could put a block but want an object initializer you need to add wrap it in () so that the { is treated as the start of an expression.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

why do we need parentheses

I guess because without them (), it won't work, throws the error even on compile time.

setCount(
  currentState => (//can not understand
    {...currentState, count: currentState.count+1}
  )
)

setCount is a setState hooks. It has 2 syntax:

  1. setCount( newStateOfCount ) (set state with direct value)
  2. setCount( oldCount => newCount ) (set state using a callback)

And yours is the second one. With the callback return an object, you have 2 options:

currentState => {
  return {
    ...currentState, 
    count: currentState.count+1
  }
} 

which is more verbose than

currentState => ({
  ...currentState, 
  count: currentState.count+1
})

So in the tutorial he used the second syntax, because it's more concise.

Without the parentheses it doesn't work:

currentState => {
  ...currentState, 
  count: currentState.count+1
}

Because the parser will understand that { is the begin of a function body, rather than an object, it won't be able to figure it out, without you explicitly give it the ()

Loi Nguyen Huynh
  • 8,492
  • 2
  • 29
  • 52
  • so basically ( ) is something let's say escape character? – Edy Dec 22 '19 at 00:31
  • @Edy Yes, I think roughly the idea is that. *Some character* is special in some context, so we need 1 extra "escape character" to make the language understand it correctly *(for that context)*. – Loi Nguyen Huynh Dec 22 '19 at 00:35