Class Components vs. Functional Components

Overview: In React there are two ways of writing a component, a functional component and a class component. Both are extremely important to understand to properly create a React App.

Functional Component: A functional component takes in props and can return JSX. In a functional component you cannot use state (often referred to as stateless components), there are no lifecycle methods, and it does not have a render method. However, props can be passed in functional components. Functional components are easier to read, test, and debug. They are also more reusable. If you are creating a large app, functional components come in handy because you will be able to read and debug your app. Overall, functional components are simpler and cleaner but cannot do as much as a Class component can.

Class Component (ES6 Classes): A class component has state (known as stateful components) and they also have lifecycle methods. With state, logic can then be implemented into the function. With lifecycle methods, the defined functions in the class will be executed during one of those methods. A class component also must have a render method returning HTML and extend React.Component. Class components are more complex than functional components since they implement state, they are also not as readable.

Many established programmers I’ve spoken to have all said that they primarily use functional components since the are simpler and easier to debug. They typically start each component as a functional component and if they need to add state, they will change it to a class component. This will vary from project to project but the difference is important to know!