Search code examples
javascriptreactjsfunctionfunctional-programmingreact-component

What is the difference between const funcName = (args) => { }; and const funcName = (args) => ( );?


I'm new to React and now I'm taking a course on Pluralsight.

Let's take this example:

const Card = (props) => {
      
      var profile = props;
      return (<div className="github-profile">
          <img src={profile.avatar_url} />
        <div className="info">
          <div className="name">{profile.name}</div>
          <div className="company">{profile.company}</div>
        </div>
        </div>);
};

This is a function component but this can be rewrite like:

const Card = (props) => (
        <div className="github-profile">
          <img src={props.avatar_url} />
        <div className="info">
          <div className="name">{props.name}</div>
          <div className="company">{props.company}</div>
        </div>
        </div>
);

What is the actual difference? Aren't the same thing? When you use () and when {}?


Solution

  • An arrow function can have one of two forms:

    1. (args) => { /* statements */ }
    2. (args) => returnValue as a shorthand for (args) => { return returnValue }

    The (args) => (...) form that you mentioned is actually just form #2 with extra parentheses (which may be necessary if returning an object literal for example, because otherwise it would be ambiguous with form #1, and they are standard for returning a JSX expression like <Thing>...</Thing>).

    If you want to do more than just returning something, you'll use form #1. Otherwise form #2 will suffice.

    (Note: If there is exactly one argument, the left-hand parentheses are optional - args => ... is the same as (args) => ...)