× logo Home HTML CSS Javascript React-App Angular.js logo

Understanding Functional Components vs. Class Components in React

In the world of React, there are two ways of writing a React component. One uses a function and the other uses a class. Recently functional components are becoming more and more popular, so why is that?

Differences between functional and class-Components
The most obvious one difference is the syntax.
A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element.

A class component requires you to extend from React.Component and create a render function which returns a React element.
This requires more code but will also give you some benefits.

Let's start with a simple example of a Functional Component in React defined as FunctionalComponent which returns JSX:

As you can see, a functional component is a function that returns JSX. If you are not familiar with arrow functions introduced in ES6, you can also check out the example below without.

On the other hand, when defining a class component, you have to make a class that extends React.Component. The JSX to render will be returned inside the render method.
Below is the same example but without using destructuring. If you are not familiar with destructuring, you can learn more about destructuring and arrow functions introduced in ES6!
See render with class component in CodePen

Passing props

Passing props can be confusing, but let's see how they are written in both class and functional components. Let's say we are passing props of the name "Jama" like below.
Inside a functional component, we are passing props as an argument of the function. Note that we are using destructuring here. Alternatively, we can write it without as well.

In this case, you have to use props.name instead of name.
See props with functional component in CodePen

Since it is a class, you need to use this to refer to props. And of course, we can use destructuring to get name inside props while utilizing class-based components. See props with class component in CodePen

Handling state in functional components
See state with functional component in CodePen
Handling state in class components
See state with class component in Codepen
Lifecycle Methods
See lifecycle with functional component in Codepen
See life cycle with class component in Codepen

The key distinction between the two is that class components have state and lifecycle method while function component do not, As long as you do not need state or lifecycle method, use a function component. logo