Basic React Types
The choice of which type definitions to use in your React + TypeScript project often depends on your specific needs, but there are some general recommendations and community preferences.
My Recommendation
Functional components
Consider avoiding React.FC if you don't require its additional properties like displayName and propTypes. Directly typing your function's props is more explicit and flexible.
Class components
Continue using React.Component<Props, State> for full benefits of TypeScript features.
Higher-Order components
Use React.ComponentType when you want to be agnostic to the kind of component being passed.
Childrencomponents
Use React.ReactNode for typing children when you want to allow a broad range of JSX elements, text, arrays, and fragments.
Community Agreement
Functional Components
There's a trend in the React community towards using functional components due to their simplicity and support for hooks. The use of React.FC or React.FunctionComponent was popular initially but has seen some debate. Some developers have moved away from React.FC due to its implicit children typing and other limitations. Instead, they opt for direct prop typing.
const MyComponent: React.FC<MyProps> = (props) => {
/* ... */
};
const MyComponent = (props: MyProps) => {
/* ... */
};
Class Components
For class components, React.Component<Props, State> is the standard and provides strong type checking out of the box.
class MyComponent extends React.Component<MyProps, MyState> {
/* ... */
}
Higher-Order Components and Library Integrations
When you're unsure whether a passed component will be a class or functional component, or when you're writing higher-order components, React.ComponentType is generally recommended.
const withFoo = (Component: React.ComponentType<Props>) => {
/* ... */
};
Children Prop
If your component accepts children, and you're not using React.FC (which includes it automatically), React.ReactNode is often recommended for typing the children prop due to its flexibility.
interface MyProps {
children: React.ReactNode;
}
JSX Elements
When you're dealing with JSX elements directly, it's common to use React.ReactElement or React.ReactElement[] for arrays of JSX elements.
const element: React.ReactElement = <div>Hello</div>;