This may surprise you, right now there is at least 4 way to create react component. All of these ways have there own pros and cons and implementation differences. Let’s discuss them and see which one is better in which cases.
Create Class Component
This is the original way to create a component when the react was the first lunch. You can still use this approach but most developers prefers modern approaches.
JS Class
After es6, you no longer need to create a class function to create a react component. Javascript has already class built-in. This style of creating component use extends keyword to create and component. Also, it gives more functionality and less boilerplate code along the way.
Function Component
Another way to create components is function component, it has less code and simple syntax compare to the previous two. React assume the return statement is your render function. In this type, props pass as arguments.
Arrow function Component
This is the least code option out of four. you can create a functional component via the arrow function syntax. This allows you to use consist of arrow syntax. With arrow syntax, you can omit the return keyword if the code on the right is a single expression. Also if you have multiple lines of JSX, you can wrap them inside single parentheses, which will make them a single expression. Props pass as argument here.
Why you should use Functional component more than Class component:
There is a number of reason you should consider using a functional component more.
=> Easier to understand. Avoid class-related craft, it is less code to write.
=> Function component avoids confusing this keyword, also eliminate needs for binding.
=> Functional component transpired less code than class component when they run through babel. This leads to a smaller bundle and better performance.
=> Easy to test.
=> Presumption, class components may be discontinued altogether in the future. After 16.8 with react, the hooks function component can be used in all used cases.
When to use class vs function component
This answer depends on the version of react you are using. with react version lower than 16.8, function component lack some key features. Only class component support state, Refs, Lifecycle methods not the function component. You can use the function components everywhere else.
After react version 16.8 function component radically improve by adding a new feature called “HOOKS”.
With react hooks you can use function component for almost everything.
Regardless of your react version it is good to use functional components.