Functions vs Classes in React? Whats the difference?

This has been bugging me for sometime -

Should I use Functions or Classes in React?

I dont see much difference in both, if anything, the functional approach seems to be easier and can do pretty much everything as same as using classes.

Is there really any difference between them ?

(Note: - Im not talking about differences like using super() or this.bind or useState used in a different way, rather if either one can do something which the other CANT. )

First there were classes. Every component was a class.

Then along came functional components. They were lighter and faster but had no state or lifecycle methods. These were sometimes called stateless functional components (SFCs). The idea was you used class components for anything that needed state or lifecycle methods and used SFCs for everything else. This is about where FCC’s curriculum is.

Now there are hooks. With them, functional components could now be “stateful” and now FCs could have functionality equivalent to lifecycle methods. In modern React, you don’t need class components.

Modern React developers often don’t use class components. I don’t use them unless I am connecting into older code that requires is.

But don’t get me wrong - it’s still very important to learn class components.

2 Likes

Error boundary components (which are very useful, and will only become moreso with react 18+ & concurrent mode) must be defined using classes, that’s the only major thing.

Otherwise functions are (IMO, YMMV) clearer and much closer a model of how React is working than class components.

3 Likes

I don’t really know what this means yet. is it something related to catching errors?

Yeah I agree .

:+1:

Yeah, the React docs are awesome. I highly recommend reading through them. Now that I think of it, it’s been a while for me…