Function Components
These can be written as normal functions that take a props argument and return a JSX element.
What about `React.FC`/`React.FunctionComponent`/`React.VoidFunctionComponent`?
You can also write components with React.FunctionComponent (or the shorthand React.FC - they are the same):
Some differences from the "normal function" version:
React.FunctionComponentis explicit about the return type, while the normal function version is implicit (or else needs additional annotation).It provides typechecking and autocomplete for static properties like
displayName,propTypes, anddefaultProps.- Note that there are some known issues using
defaultPropswithReact.FunctionComponent. See this issue for details. We maintain a separatedefaultPropssection you can also look up.
- Note that there are some known issues using
It provides an implicit definition of
children(see below) - however there are some issues with the implicitchildrentype (e.g. DefinitelyTyped#33006), and it might considered better style to be explicit about components that consumechildren, anyway.
As of @types/react PR #46643 (TODO: update with @types/react version when merged), you can use a new React.VoidFunctionComponent or React.VFC type if you wish to declare the accepted children explicitly. This is an interim solution until FunctionComponent will accept no children by default (planned for React 18).
React.VoidFunctionComponent or React.VFC type if you wish to declare the accepted children explicitly. This is an interim solution until FunctionComponent will accept no children by default (planned for React 18).- In the future, it may automatically mark props as
readonly, though that's a moot point if the props object is destructured in the parameter list.
In most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of React.FunctionComponent.
Minor Pitfalls
These patterns are not supported:
Conditional rendering
This is because due to limitations in the compiler, function components cannot return anything other than a JSX expression or null, otherwise it complains with a cryptic error message saying that the other type is not assignable to Element.
Array.fill
Unfortunately just annotating the function type will not help so if you really need to return other exotic types that React supports, you'd need to perform a type assertion: