When to use functional component over class component in ReactJS

Well, I chose this topic because I have seen people writing all over class components. This is an old topic still people are confused when to use which one. So in this article, you will see when to use functional component over class component in ReactJS.

Before we see which one to use when. Lets first know what they do likely you will get an idea also when to avoid class components.

Class Components

Usually, this is the component we use when we start learning React JS in the beginning. Class or stateful component, yes we know this component also called state component.

This component maintains/holds state throughout the class. So each component can have its own states. Let’s see an example of class component.

class greetMe extends React.Componet {
	constructor() {
		this.state = { key: value };
	render() {
		return 'hello';

Functional Components

Also known as classless components because they can not have their own states and access this keyword. Although React JS introduced Hooks, with hooks functional component can have their own states. Let’s talk about hooks later. So Functional components are nothing but normal javascript functions. For example, you can see the below code can be called functional components.

//regular function
function greetMe() {
	return <h1>hello </h1>;
//arrow function
const greetMe = () => {
	return <h1>hello </h1>;

Functional components can have props but they can not have states. It is easy to compare to the class component. The functional component does not even have lifecycle methods.

When to use Functional over Class component

By now you might have got an idea. Let’s see how much you are close from my point of view. So when to use functional component over class component in ReactJS are as follows

  • We just learn that the functional component does not have lifecycle methods so when you don’t need a lifecycle method you can go for a functional method.
  • when your sole focus is UI not behavior
  • When your component does not need states.
  • Use functional components because this can save a few lines of code.
  • Since functional components do not have any side effects, this makes them easy to test.

So this was all my perspective is regarding Functional components , Its best practice always to stick with Functional components. You can make convert any functional component into class component any time, so start with functional component. They are lighter , easier, decrease code complexity.

I hope this article helped to know something extra. Let me know what you think in the comments section.


see also

Leave a Reply

Your email address will not be published. Required fields are marked *