3

What's the difference between function declaration and arrow functions for create react components (Not the functions inside the component that we need to bind)!

Old versions of reactjs when you run create-react-app, creates the App component as an arrow function!

export const App = (props) => {}

And the newest version creates as a function declaration

function App() {}

  • Possible duplicate of [Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable) – VLAZ Jun 19 '19 at 17:06

1 Answers1

3

I would say that this is a bit opinionated choice really. There are at least several reasons why I (personally) see arrow function use for pure functional component as pretty bad practice. Here are those:

Syntax abuse. When we define function component we don't need to prebind its context to specific scope. The context (this) is going to be undefined anyway in the module namespace. The use of arrow functions is dictated here by pure aesthetics reasons like conciseness. But arrow functions as language feature has very specific purpose for existence in the first place, and this is not coolness and conciseness.

Error stacktrace. Exceptions thrown in arrow function will be less descriptive because arrow function is anonymous by definition. This is not the huge problem probably since React project will most likely be configured with proper source maps support, but still stack trace will be a bit more clear if named function is used. As noted in comments this is not really an issue of the functional component, as the name will be the name of the variable basically.

Less convenient logging. Consider this very typical pure function component style:

const Header = ({ name, branding }) => (
  <header>
    ...
  </header>
)

In the function above it's impossible to throw in quick debugger statement or console.log. You will have to temporarily convert it to something like this

const Header = function ({ name, branding }) { 
  console.log(name)
  return (
    <header>
      ...
    </header>
  )
}

This might be pretty annoying especially for bigger pure components.

That being said this is very popular choice for many teams, also by default preferred by ESLint, so if you don't see the problem with it, then it is probably okay.

Brad Ball
  • 599
  • 3
  • 5