Sub topic 5
React.FC or a plain function?
This chapter assumes you can write function components with typed props, as covered in the earlier chapters. It compares the two common ways to declare a component's type and gives you a rule for choosing between them.
The two styles
You can type a function component in two ways. The first annotates the props parameter of an ordinary function. The second annotates the variable with React.FC, short for React.FunctionComponent.
import type { FC } from "react";
interface GreetingProps {
name: string;
}
// Style 1: plain function. The props parameter carries the type.
export function Greeting({ name }: GreetingProps) {
return <p>Hello, {name}</p>;
}
// Style 2: FC. The variable carries the type.
export const GreetingFC: FC<GreetingProps> = ({ name }) => {
return <p>Hello, {name}</p>;
};Both components accept the same props, and both can be used as <Greeting name="Ada" />. The difference is where the type is attached and what extra behavior the annotation brings along.
What React.FC adds
FC<P> is a type alias for a function that takes props P and returns something renderable. It also declares optional static properties on the function object:
displayName, a string used in React DevTools.propTypes, for runtime prop validation. Most TypeScript projects don't use it.defaultProps, the legacy way to set default prop values.
The annotation also checks the return type. If you return something React cannot render, the compiler reports an error at the declaration instead of at the place where you use the component.
import type { FC } from "react";
export const Badge: FC<{ label: string }> = ({ label }) => (
<span>{label}</span>
);
Badge.displayName = "Badge"; // allowed because FC declares displayNameIn older code you may also see React.FC used to get an implicit children prop. That behavior is gone, as the next section explains.
The history of implicit children
Before version 18 of @types/react, FC<P> quietly added children?: ReactNode to every component's props. This caused two problems:
- A component that never renders children still accepted them, so
<Badge label="x">ignored text</Badge>compiled without error. - Readers could not tell from the props interface whether a component used
children.
Version 18 of the types removed the implicit prop. Today FC and a plain function behave the same here: if a component takes children, you declare them yourself.
import type { FC, ReactNode } from "react";
interface PanelProps {
heading: string;
children: ReactNode;
}
export const Panel: FC<PanelProps> = ({ heading, children }) => (
<section>
<h2>{heading}</h2>
{children}
</section>
);If you maintain a codebase pinned to an old @types/react, check the version before assuming children are checked. Upgrading the types can then produce many new errors. Each one marks a component that was relying on the implicit prop.
Where plain functions win
The community has mostly moved toward plain functions, for these reasons.
Generics
A plain function can declare its own type parameter. A variable annotated with FC cannot, because the type parameter has no place to be declared.
import type { ReactNode } from "react";
interface ListProps<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
// Plain function: T is inferred from items.
export function List<T>({ items, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
);
}
// An arrow function in a .tsx file needs a trailing comma so that
// <T,> is not parsed as a JSX tag.
export const ListArrow = <T,>({ items, renderItem }: ListProps<T>) => (
<ul>
{items.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
);With FC you would have to fix T to a concrete type, which defeats the purpose of a generic component. The chapter on generic components covers this in detail.
Return types and newer component kinds
FC fixes what a component may return. Plain functions are checked by how JSX uses them, and newer versions of React and the types accept more kinds of components, such as async server components. Annotating with FC can block a component shape that the framework accepts. A plain function has no such limit.
Less indirection
A plain function shows its props type where you read the code. You can hover over the parameter, and the function name appears in stack traces and DevTools without extra work. A function declaration also has a name in the call stack, while an anonymous arrow assigned to a const gets its name from the variable, so both are fine.
Defaults
Default values work the same way in both styles. You set them in the destructuring pattern, as in the earlier chapter on optional props. Avoid defaultProps in new function components. React has deprecated it for function components, and TypeScript's handling of it adds complexity.
When FC is still reasonable
FC has a few legitimate uses:
- Your team's existing code uses it consistently, and a mixed style would cost more than it gains.
- You want to attach
displayNameor other statics with the compiler checking them. - You want to declare a component's type separately from its implementation, for example a variable of type
FC<Props>assigned in one place and defined in another.
For the second case, a plain function can also carry statics. Object.assign attaches them and TypeScript tracks the result:
interface TabProps {
title: string;
}
function TabBase({ title }: TabProps) {
return <button>{title}</button>;
}
export const Tab = Object.assign(TabBase, { displayName: "Tab" });Comparing the two
| Concern | Plain function | `React.FC` |
|---|---|---|
| Implicit `children` | No | No (types 18 and later) |
| Generic components | Yes | No |
| Type shown at | The parameter | The variable |
| Return type check | Through JSX usage | At the declaration |
| Typed statics such as `displayName` | Via `Object.assign` | Built in |
| Common in new code | Yes | Less so |
Return type annotations
You rarely need to annotate a component's return type. TypeScript infers it from the JSX you return. If you do want an explicit annotation, use ReactNode for anything renderable, or ReactElement if you always return an element:
import type { ReactNode } from "react";
export function Maybe({ show }: { show: boolean }): ReactNode {
return show ? <p>Visible</p> : null;
}Avoid the global JSX.Element type in new code. Newer versions of @types/react moved it into the React namespace, so a global JSX reference may stop compiling.
Common mistakes
- Expecting
childrenfor free. Under current types,FC<{ title: string }>rejects children. Declarechildren: ReactNode. - Writing
<T>in an arrow function in a.tsxfile. The parser reads it as a JSX tag. Use<T,>or<T extends unknown>, or use a function declaration. - Using
defaultPropswith function components. Use default values in destructuring. - Annotating the props and the variable. Writing
const A: FC<Props> = ({ x }: Props) => ...repeats the type and adds nothing.
Exercise
A teammate writes const Table: React.FC<TableProps<T>> = ... for a table that should accept rows of any type, and the compiler reports that it cannot find the name T. What is the problem, and how do you fix it?
Show answer
A variable annotated with React.FC has no place to declare the type parameter T, so T is not in scope. Rewrite the component as a plain function with its own type parameter: function Table<T>({ rows }: TableProps<T>) { ... }. In a .tsx file an arrow function version must be written <T,>(props: TableProps<T>) => ....
Exercise
Your project uses @types/react 18. A component is declared as const Note: FC<{ text: string }> = ({ text }) => <p>{text}</p>, and someone renders <Note text="a">extra</Note>. Does it compile? What changes if the project is on @types/react 17?
Show answer
With the version 18 types it does not compile, because children is not part of the props and the extra child is rejected. With the version 17 types it compiles, because FC adds an optional children prop to every component, even though Note ignores it.