DEV Community

tpostolyuk
tpostolyuk

Posted on

Why do we have to write functional instead of class components?

Yo! Today we talk about nowadays of ReactJS. The front-end industry is growing up increasingly, and we have to get used to it and prepare for all changes in the programming that can happen.

Recently, we write all ReactJS applications on class components. Now, we have React Hooks that provide our functional component, for example, with the state.
Well, let's talk about the advantages of the functional components. Take a look at this small class that just handle change
and render it.
Class component

It looks a bit great. Next, I rewrite this component to functional.
Functional component

Well, it is a small example, but even it shows us how functional components reduce code, and it is the first advantage.

Functional components reduce approximately 25 percent of code that is in class components

The second reason is that React is going to functional programming.
The official documentation says that it is good to
practice using Hooks in new and non-critical components. It does not mean that class would not be supported in the future, it will.

The third reason is not to think about context.
If you write on class, you always thinking about how not to lose context and bind all methods. In the function, you can forget about it in most situations that can happen.

The last reason is reusability. In the function, you can reuse logic, for example, by creating a custom hook and reuse it in every component you want. In class, you can't do it, you must rewrite the whole component.

So, I recommend you to write functional instead of class components.

Top comments (1)

Collapse
 
fralainbk profile image
Franck Binde

It's always great to get insights about class based components and functional components. Thank you for these informations.