DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Typing React Components: React.FC or JSX.Element?
Ben Hur Martins Carvalho
Ben Hur Martins Carvalho

Posted on

Typing React Components: React.FC or JSX.Element?

Typing a React/React Native component is not always necessary, the type usually is implicit by the return statement, but sometimes we need to, and there are some approaches to type it.

Probably the most common is using the interface already provided by react: FC, which means Functional Component, if the component accept props we only need to add the prop types on it: FC.

The other which is implicit by the return type is JSX.Element and widely used as well, and, before React 18, this approach was more reliable.

Cons of using React.FC

Before React 18 there were a potential issue using FC, it has an implicit children props on it as default, so anyone using a component with the FC type could pass a children on it:


That is not an issue anymore, since in React 18 it got removed, so if your project runs on 18 or higher, no need to worry about that.

Cons of using JSX.Element

This is the implicit return type if you don't declare it. But let's suppose your component will not always return a valid JSX.Element, sometimes we want to return null or just a piece of string, JSX.Element will not be enough and we will start to add other return types: JSX.Element | null:

Not typing components

This is also an option, and probably will work fine, typescript can understand and work with implicit types, only won't work if your project enforces eslint rules that requires to type explicitly everything.

Usage exemples

A basic exemple with the same button type with the same function and two different types:

Conclusion

I can't see a good reason to use one option over another, JSX stills have the useage more strict by not allowing returning strings or null values, but it also is not a big deal to not use it. In the end it is more a matter of what type we want to use in our project or even not typing stills a choice.

My personal choice is using React.FC, most of the new typescript users find it easier to use, and in my opinion it makes the code easier to read.

Top comments (1)

Collapse
 
monotype profile image
Pavlo

Should I explicitly set React.FC on each components even If it does not have props? Because now I usually use React.FC to anotate prop types like that React.FC

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.