Skip to content Skip to sidebar Skip to footer

Function Or Fat Arrow For A React Functional Component?

I can't help but wondering if there's any advantage between using plain functions and fat arrows for React functional components const MyMainComponent = () => (

Solution 1:

There is no practical difference.

An arrow allows to skip return keyword, but cannot benefit from hoisting. This results in less verbose output with ES6 target but more verbose output when transpiled to ES5 , because a function is assigned to a variable:

var MyMainComponent = function MyMainComponent() {
  return React.createElement(
    "main",
    null,
    React.createElement("h1", null, "Welcome to my app")
  );
};

The overhead is 6 bytes in minified and not gzipped JS file, this consideration can be generally ignored.

Verbosity is not necessarily the case when an arrow is exported, due to optimizations:

varMyMainComponent = (exports.MyMainComponent = functionMyMainComponent() {
  returnReact.createElement(
    "main",
    null,
    React.createElement("h1", null, "Welcome to my app")
  );
});

Solution 2:

Mostly a matter of preference. However, there are some (minor, almost insignificant) differences:

  • The fat arrow syntax lets you omit the curly braces and the return keyword if you return the JSX directly, without any prior expressions. With ES5 functions, you must have the { return ... }.

  • The fat arrow syntax does not create a new context of this, whereas ES5 functions do. This can be useful when you want this inside the function to reference the React component or when you want to skip the this.foo = this.foo.bind(this); step.

There are more differences between them, but they are rarely relative when coding in React (e.g using arguments, new, etc).

On a personal note, I use the fat arrow syntax whenever possible, as I prefer that syntax.

Post a Comment for "Function Or Fat Arrow For A React Functional Component?"