Converting Class Components into Functional Components (REACT)

Mo Zahid
2 min readJul 13, 2021

--

A Rant

If class components are your go-to within React or you need to quickly convert a class component into a functional component, then this blog will be a topic of great interest. I have many friends that are Software Engineers and I have yet to speak to one that is currently utilizing class components within a production environment. To folks currently riding the coding the bootcamp wave, I would suggest you steer that car away from these relics of the past. If you have a choice between class and functional…go functional every time!!! You don’t want your default coding style to be outdated. This topic hits close to home for me because my default was definitely class components. Switching over was not a huge deal. But if your still kind of new to coding I would expect switching abruptly would greatly reduce your speed when coding. Let’s solve this with some points on transforming class components to functional components!

A Class Component Example

The above is a very simple example of a class component. You will quickly notice how easy it is to initialize state in class components (the example on line 9). Class components also require line 1 as an import. In this component we are using a simple function called “buttonHandler” which changes state. Notice that it does not have a “const” or “let” Infront of it. In addition, on line 29 we also have “this.buttonHandler”. The magic word “this” is very specific to class components.

A similar Functional Component

Let’s look at a similar functional component example. We do not need to import “Component” when working with functional components. However, we do need to import “useState” (line 2). This will allow us to import the hook which allows us to work with “state” within functional components. Line 8 which initializes state will allow us to retrieve the current state with the word “color” and set the state with “setColor”. You can choose words that make sense for your project. Also, our function on line 11 has a “let” in front of it. There is no magic “this” keyword with functional components so when we call this function on line 22 we simply write “buttonHandler”.

Conclusion

And there you have it! Class components are a thing of the past. Use functional components when you can. Don’t be the person that only knows how to use class components…I was that guy. Get super comfortable with what is most relevant today!

--

--