DEV Community

tpostoliuk
tpostoliuk

Posted on

5 2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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.

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay