Function or fat arrow for a React functional component? [duplicate]

眉间皱痕 提交于 2020-08-22 09:22:12

问题


I can't help but wondering if there's any advantage between using plain functions and fat arrows for React functional components

const MyMainComponent = () => (
  <main>
    <h1>Welcome to my app</h1>
  </main>
)

function MyMainComponent() {
  return (
    <main>
      <h1>Welcome to my app</h1>
    </main>
  )
}

Both work of course perfectly fine but is there a recommended way to write those ? Any argument in favor of one or the other ?

Edit: I am aware of the differences when it comes to plain javascript functions (i.e. context, stack trace, return keyword, etc.) that can have an impact for the kind of use you have for functions. However I am asking the question purely in terms of React components.


回答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:

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



回答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.



来源:https://stackoverflow.com/questions/54331084/function-or-fat-arrow-for-a-react-functional-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!