Functional or Class component in ReactJs?

Deepak Mankotia
2 min readApr 5, 2023

In React, you can create components using two different approaches: functional components and class components. Here’s a brief overview of both:

  1. Functional Components: Functional components are stateless and are defined as JavaScript functions. They receive props as arguments and return the UI to be rendered based on those props. Functional components are simple, lightweight, and easy to understand, as they do not have their own internal state or lifecycle methods. Functional components are recommended in modern React applications, as they are considered the best practice for creating reusable UI components.

Example of a functional component:

import React from 'react';

const MyComponent = (props) => {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>{props.message}</p>
</div>
);
};

export default MyComponent;

2. Class Components: Class components are based on ES6 classes and are the traditional way of creating components in React. Class components have their own internal state, which can be accessed and modified using this.state and can also have lifecycle methods such as componentDidMount and componentDidUpdate for handling side effects. However, class components are generally more complex and harder to understand compared to functional components.

Example of a class component:

import React, { Component } from 'react';

class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

componentDidMount() {
// Side effect logic
}

render() {
return (
<div>
<h1>Hello, {this.props.name}!</h1>
<p>{this.props.message}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
<p>Count: {this.state.count}</p>
</div>
);
}
}

export default MyComponent;

In general, it is recommended to use functional components as much as possible in modern React applications, as they are simpler, easier to test, and easier to reason about. However, there may be cases where class components are necessary, such as when you need to manage internal state or work with legacy code. It’s important to understand the differences between functional components and class components and choose the appropriate approach based on the specific requirements of your project.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Deepak Mankotia
Deepak Mankotia

Written by Deepak Mankotia

Full Stack Web Developer | Open Source Enthusiast

No responses yet

Write a response