Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is React.FunctionComponenent preferred over conventional function definitions?

I've always defined React components (with typescript) as:

function MyComponent(props: PropsType): React.ReactElement | null {
    //...
}

Online I see a lot of examples like:

const MyComponent: React.FC = (props: PropsType) => {
    //...
}

I understand they are pretty much the same, but what is the preferred convention in the Typescript community?

like image 680
user3690467 Avatar asked Aug 13 '19 13:08

user3690467


People also ask

Why are functional components preferred in React?

Functional component are much easier to read and test because they are plain JavaScript functions (less code). The React team mentioned that there may be a performance boost for functional component in future React version.

Is it better to use functional components React?

React recommends that Functional Components are used over classes, and even will throw warnings about a few Class Component lifecycle methods that are being deprecated.

What is the difference between component and function in React?

The most obvious one difference is the syntax. A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element. A class component requires you to extend from React. Component and create a render function which returns a React element.


1 Answers

Quoting React-Typescript Cheatsheet on Github

You can also write components with React.FunctionComponent (or the shorthand React.FC):

const App: React.FC<{ message: string }> = ({ message }) => (  
  <div>{message}</div>
); 

Some differences from the "normal function" version:

  • It provides typechecking and autocomplete for static properties like displayName, propTypes, and defaultProps - However, there are currently known issues using defaultProps with React.FunctionComponent. See this issue for details
  • It provides an implicit definition of children (see below) - however there are some issues with the implicit children type (e.g. DefinitelyTyped#33006), and it might considered better style to be explicit about components that consume children, anyway.
const Title: React.FunctionComponent<{ title: string }> = ({  
children, title }) => <div title={title}>{children}</div>;
  • In the future, it may automatically mark props as readonly, though that's a moot point if the props object is destructured in the constructor.

  • React.FunctionComponent is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).

In most cases it makes very little difference which syntax is used, but the React.FC syntax is slightly more verbose without providing clear advantage, so precedence was given to the "normal function" syntax.

like image 195
Agney Avatar answered Oct 08 '22 23:10

Agney