Reactjs setState arrow function syntax Reactjs setState arrow function syntax reactjs reactjs

Reactjs setState arrow function syntax


There are 2 main issues to consider here:

  1. How arrow functions works?

  2. What setState expects when passing function as a parameter?

Answers:

  1. Arrow functions can return a value implicitly or explicitly.
    Whenthere is no function body (no curly brace {}) then you arereturning implicitly:

    const x = () => 'we are returning a string here';  

    When we use a function body, we need to use the return key word:

    const x = () => {  return 'another string returned'};

    There is another option to return something without the return keyword, you can wrap the curly brace with parentheses () and thiswill signal the engine that the curly brace are not a function bodybut an object, this is considered as creating an expression:

    const x = () => ({myKey: 'some string'});

    This is similar as we usually do with function expressions.
    Especially with IIFE (Immediately Invoked FunctionExpression) :

    (function() {    //some logic...})();  

    If we will not return anything, then the function will just return undefined.

  2. As for setState, when you pass a function as a parameter, itexpect that this function will return an object.
    When your function didn't return anything (as stated above) it actuallyreturned undefined.
    JavaScript won't yield an error as this is notan error. its just a function that returns nothing (undefined).

Here is a running example of your code without the wrapping parentheses:

class Toggle extends React.Component {  constructor(props) {    super(props);    this.state = {      isToggleOn: true    }    this.handleClick = this.handleClick.bind(this);  }  handleClick() {    this.setState(prevState => {      return { // we must return an object for setState        isToggleOn: !prevState.isToggleOn      }     });  }  render() {    return (      <div>        <button onClick={this.handleClick}>          {this.state.isToggleOn ? 'ON' : "OFF"}        </button>      </div>    );  }}ReactDOM.render(<Toggle />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>