What's the difference between a React.FunctionComponent and a plain JS function component?

Viewed 28294

These two examples accomplish the same thing. But what are the differences under the hood? I understand functional components vs. React.Component and React.PureComponent, but I haven't been able to find relevant documentation about React.FunctionComponent.

React.FunctionComponent

const MyComponentA: React.FunctionComponent = (props) => {
  return (
    <p>I am a React.FunctionComponent</p>
  );
};

Plain JS function component:

const MyComponentB = (props) => {
  return (
    <p>I am a plain JS function component</p>
  );
};
3 Answers

There is no difference under the hood. The first one is using TypeScript syntax to indicate the type of React.FunctionComponent but they are both plain JS function components.

there are some minor differences, plain function component could return string, like:

const FooString = () => "foo";

but you couldn't return string from a FunctionComponent.

const BarString: React.FC<{}> = () => "string";

hence the return type must be ReactElement|null

The difference is that FunctionComponent comes with one property by default: children


// Note, no children defined
type Props = {
  name: string
}

const MyComponentA: React.FunctionComponent<Props> = (props) => {
  return (
    <p>I am a React.FunctionComponent and my name is {props.name}</p>
    <p>And I have {props.children}</p>
  );
};

const MyComponentB = (props: Props) => {
  return (
    <p>I am a plain JS function component</p>
    <p>But my {props.children} are undefined</p>
  );
};

For MyComponentB the TS compiler would complain that children is not defined.

Of course for both components you can just pass children and ignore the TS warning.

Related