React Native Docs Example with ES6

Viewed 50

The below code is from React Native Docs. As you can see, there are two function declerations with fat arrows. I understand the usage of normal parenthesis with the line containing .... previousState => ({ etc. Here use of () is needed because it returns an object literal. However, I can't understand why do we use "(" with the callback function of the setInterval. I mean this line: setInterval(() => ( .... Why we do not write like setInterval(() => { .....

class Blink extends Component {

  componentDidMount() {

    //HEART OF THE QUESTION. Why do we use "(" below, instead "{". Do we need to return for setInterval or just define a function to run ?
    setInterval(() => ( 
    
      //Here, "(" is normal because it returns object literal
      this.setState(previousState => ({
        isShowingText: !previousState.isShowingText
      }))
    ), 1000);
  }

  //....

}

1 Answers

setInterval doesn't need a return. Both of these will work perfectly fine:

setInterval(() =>
    this.setState(previousState => ({
        counter: previousState.counter + 1 || 1
    })),
1000);

and this (which is not pretty without parenthesis, in my opinion):

setInterval(() => {
    this.setState(previousState => ({
        counter: previousState.counter + 1 || 1
    }));
}, 1000);

Usually parenthesis is needed for multiline returns, here is a good explanation: http://jamesknelson.com/javascript-return-parenthesis/

Related