Class vs Functional Components in React

Erik Nielsen
2 min readMar 22, 2021

I have been working on a React app for my final project at Flatiron School. Something that I ran into about three quarters of the way through is the difference between and more importantly when you should and should not use class and functional components. The reason I felt this would be a great topic to discuss is, I was asking my teacher a question about my project and he seen one of my components was a class component but it was just a simple stateless component. He asked why are you using a class component? This made me think well, I don’t know, I’m only using class components.

This was what started my research and lead to this blog post. First off the biggest difference is syntax class components are defined like so.

And functional components like so.

Function components have an advantage of less code, just from the above examples you can tell they the function component is more simple. Another advantage is the functional component looks just like a plain JavaScript function.

If functional components are so simple why use class components at all? Well there is a few reasons, one being lifecycle methods. ComponentDidMount was a method I used heavily in my React App and makes it important to use class components. The other reason to use class components is when your component uses state. Through my research I have learned that state and lifecycle methods can be utilized in functional components using hooks, but that is a whole other topic I will dive into with another blog post.

My issue with not utilizing the correct style of component came down to my perception that object oriented programming is superior to procedural programming so I should use classes for everything. The reality is that it was just a lack of understanding of React and how to make your code simple and readable to other programmers. In my short journey so far I have come a long way and I have my work still to do, but I have enjoyed the journey. Thanks for reading.

--

--