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?
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.
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.
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.
Quoting React-Typescript Cheatsheet on Github
You can also write components with
React.FunctionComponent
(or the shorthandReact.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
, anddefaultProps
- However, there are currently known issues usingdefaultProps
withReact.FunctionComponent
. See this issue for details- It provides an implicit definition of
children
(see below) - however there are some issues with the implicitchildren
type (e.g. DefinitelyTyped#33006), and it might considered better style to be explicit about components that consumechildren
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With