React Components: Functional vs Class

Bahay Gulle Bilgi
Analytics Vidhya
Published in
3 min readFeb 17, 2020

React components are independent and reusable code blocks that return a React element. Functional Components and Class Components are two main types of components in React:

  1. Functional Components: They are basic functions that accept props as an argument and return JSX code instead of using a render() method. Functional components can be declared by both JavaScript functions and arrow functions. You will need to explicitly write props as the argument and you do not need to extend Component to work with functional components.
<RecipeList> functional component creates <li> elements.

Functional components are also known as stateless components because they do not store state and they lack lifecycle methods and instances. Functional components can also be written as a single line with ES6:

It takes up less lines of code to write down the same <RecipeList> functional component with ES6.

Functional components are easier to write, read, understand, test and debug. They are mostly used to display content without any heavy logic, but they can be more complex if you want to use helper functions and React Hooks (version 16.8). Functional components should be favored until unless you need state and lifecycle methods, which are easily available to class components.

2. Class Components: In React, the components can also be declared as classes. As its name suggests, class components are created using the ES6 class syntax and they differ from functional components in several ways. First of all, class components need to be extended from a Component class, which gives access to all the functions of the parent component. Second, they require a render() method to return a React element (JSX code).

In addition to render() method, we can add also Lifecycle methods inside class components. Class components are also known as stateful components because they take constructor function, where they can accept props and maintain their own data with state. Lastly, you can have access to props with this.props because class components have instances.

Note that the componentDidMount() lifecycle method is used inside <RecipeContainer> class component.

In summary, functional components are concise and easier to understand and maintain. They are good options for simple components, but they lack certain features. On the other hand, class components implement logic and they are more complex than functional components by including state, Component class, constructors, lifecycle and render() methods. It is suggested to start with a functional component unless you need state and lifecycle methods because functional components can not perform these additions unless React Hooks is used.

--

--