Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>   ); }; 
like image 834
jacobsowles Avatar asked Dec 26 '18 18:12

jacobsowles


People also ask

What is the difference between component and function in React?

The most obvious one difference is the syntax. A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element. A class component requires you to extend from React. Component and create a render function which returns a React element.

What is Functioncomponent in React?

A React functional component is a simple JavaScript function that accepts props and returns a React element. After the introduction of React Hooks, writing functional components has become the ​standard way of writing React components in modern applications.

Should I use React component or function?

Although we should prefer using function components most times as React also allows using state with function components in React version 16.8 and later by using the useState hook, which is also recommended by Meta (Facebook App) itself.

Which is better functional component or class component in React?

Nothing is better, because both have pros and cons. But class components are important to understand React flow and lifecycle methods. The new learner should practice React using class components. Once they are familiar with class components, they can learn and use functional components.


2 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.

like image 128
Ryan Cogswell Avatar answered Sep 30 '22 14:09

Ryan Cogswell


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

like image 33
xiechao06 Avatar answered Sep 30 '22 14:09

xiechao06