Functional Components vs Class Components in ReactJs

In this article I’m going to show you the differences between functional components and class components in react.

There are mainly two components in React:

  • Functional Components
  • Class Components

So before anything let’s understand what is Component?

Component is a base building block of any react application.It is a JavaScript class or maybe a function which accepts inputs(properties or Props) and return React elements that shows how the User Interface need to be visible.

You can go through this to know more about components and props.

When we describe a component using functional component it is like this,. function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

But when its comes to ES6 class or class component you can write like this,,.. class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

After render you will see the same output is returned. Now the question will arise in your mind ..!Which one should i use?

Let’s understand more about both the components so that you can choose your own.

Functional Components

  • Functional Components are basic JavaScript functions.
  • Typically arrow functions but also can be created with regular function keyword.
  • Mainly responsible for rendering UI’s(User Interface).
  • There is no render method used in a functional component.
  • We are not allowed to use Componentdidmount() in functional component.

Class Components

  • Make use of ES6 class and extend the Component class in react.
  • Its tend to implement logic and state because of that its called “smart” or “stateful”component.
  • React life cycle methods can be used within the class component.
  • Can pass props and can be access props by using this.props.
  • There is huge support for class components in stackoverflow and in other community groups too.

Differences between functional and class Components

Syntax: The most obvious difference is the syntax.Functional component is just a plain JavaScript function which will accepts properties and arguments and return elements.

When it comes to class components its required to extend from React.Component and render function returns React element.

After the React hooks update the things get little bit easier and simple.

Why i recommend you to use functional components?

There are some advantages:

  • Functional components are easier to read and its testable(because these are plain JavaScript functions).
  • It’s easy to separate container and presentational components.
  • Can easily use best practices.
  • It is easy to maintain.

So,guys this is the basic thing which you need to know about functional and class components.

If you want to connect with me..Feel free to get in touch i love to learn and share.

I am a frontend developer who love to learn and share.