.app-desktop{ --postPageVerticalPadding: 0px !important; }
top of page

Why You Should Use the React.FC Type for Components

One of the beauties of Typescript is its strong emphasis on static typing. However, in some areas, this feature gets thrown out in favor of inference. Components are a great example of this—with types often being neglected.

This post is an effort to remind you of the benefits of adding types to any component you’re working on.

Typically you’ll find, or make, components like this:

Inherently, there isn’t anything wrong with this. It will absolutely work, and we can go about our day.

However, when working on large code bases, predictability and testability become necessities.

If you write a component like this, its type will be JSX.Element. What can we do with that outside of actually implementing it as a component? Not much.

But if we add React.FC (or React.FunctionComponent) to the component type, things change:

Suddenly we get access to some interesting properties which are useful for testing. Additionally, if we use props, one thing that isn’t immediately obvious from this list is that we gain an inherent children type.

This is quite useful, because we don’t have to define a custom type for them in our prop anymore. They’re there as just default, optional behavior.

If you’re new to the React paradigm, using children can be nebulous, and I find that React.FC helps clear the air on what hidden properties are out there.

You might be of the opinion that it’s better to have children defined manually in your types, and that’s okay too. You can still do that in this case, which simply overrides the default React.FC from optional to required, or whatever you implement.

The type protection we gain can also save us some headaches during the actual implementation of a component. Consider the following, where we have no errors in a conditional render inside the component itself, and we only get the error when using it somewhere else:

If we add the React.FC type, the blame shifts to the source, and stops us from finishing our work on the component until its return conditions are defined properly.

Remember, using React.FC doesn’t mean the return type changes. A React.FC type component still returns a JSX.Element!

One additional change available using this type is prop types.

In a large code base, we try to keep interface usage down to a minimum and leave them defined in definition files. The change needed when using React.FC is that we define our prop types in the component type, instead of the prop variable:

I hope this topic was useful for you. The additional properties I showed earlier like contextTypes and displayName are better explained through a topic on unit testing, and I wanted to keep this topic focused simply on the implication of using the React.FC component type.

Written by David Crawford, Mobile App Developer

88 views0 comments


bottom of page