Should I use a function or an arrow function for react components when using typescript?

Viewed 1256

I'm confused because I know I can do a function expression like this:

import React from 'react';
import './App.css';

 const App: React.FC = ({children}) => {
  return (
   <div className="App">
    {children}
   </div>
  );
 }

 export default App;

But for example react create app scaffolds the project using a regular function declaration and it does not need to be typed with React.FC but if I want to add props like children I would have to type the props like this:

import React from 'react';
import './App.css';

function App({children}: {children: JSX.Element}) {
 return (
  <div className="App">
   {children}
  </div>
 );
}

export default App;

Which it does not make sense to me if I can do an arrow function or even a regular anonymous function expression with React.FC like this:

import React from 'react';
import './App.css';

 const App: React.FC = function({children}) {
  return (
   <div className="App">
    {children}
   </div>
  );
 }

 export default App;

and I don't need to add any types for the children prop.

So the question is, what is the preferred way, assuming react create app scaffolds the app using a regular function declaration. But by doing that I lose the React.FC explicit stuff like the children prop that I get by doing a function expression.

1 Answers

Aside from preference, there IS a difference.

When using const Component: React.FC<Props> = (props) => {}, it actually provides type information for these component properties:

  1. propTypes
  2. defaultProps
  3. displayName
  4. ...and some other less used props

When using function Component(props: Props): JSX.Element {}, there will be no type information of the above properties.

There is no practical difference in terms of running your React code.

All it does is that it will provide you with type information + IntelliSense code autocompletion, which doesn't matter at runtime.

Which is why it boils down to "preference".

Related