React Components Explained | Functional vs Class Components
React Components Explained | Functional vs Class Components
Introduction:
In React, components are the building blocks of any application’s UI. They allow developers to break down complex interfaces into smaller, reusable pieces, making code more organized, maintainable, and easier to debug.
It is the most useful JavaScript library for creating a single-page application. It encapsulates reusability, flexibility, maintainability and UI data logic. It helps developers manage the user interface and reusable and manageable components.
In this article, we will discuss React components and compare functional components and class components from basic to advance. How to work with hooks and lifecycle methods?
React Components
React Components helps to manage the UI, single-page applications, virtual DOM, etc. With the use of virtual DOM, React creates faster updates of your webpage and applications as well. Its approach makes applications easier to maintain, build and make fast. If the developers are creating a single-page application using React.js, updating the DOM elements is a very difficult task, solved using the component-based architecture.
Types of React Components
Components are divided into two types that are shown below in detail:
1. Functional Components:
You can declare the functional components by using the function keyword. It is also known as the stateless component. It's not allowed to use a lifecycle method and a constructor. With the use of this component, you can also use a React hook. It returns the JSX element in the result, not the state. And, it contains less code as compared to class components.
1) Syntax:
import React from "react";
const Message = function(props) {
return (
<div>
<h2>{props.text}</h2>
</div>
);
};
export default Message;
2) Syntax: (With Arrow function)
const ComponentName = (props) => {
return (
<div>
{/* JSX code goes here */}
</div>
);
};
export default ComponentName;
Example
Code:
import React from "react";
const BookList = () => {
const books = [
{ id: 1, title: "Learning React", author: "Alex Banks", year: 2013 },
{ id: 2, title: "JavaScript: The Good Parts", author: "Douglas Crockford", year: 2008 },
{ id: 3, title: "C Programming Language", author: "Robert C. Martin", year: 2009 },
{ id: 4, title: "ReactJS Tutorial", author: "Marijn Haverbeke", year: 2018 }
];
return (
<div>
<h2>Book List with Functional Components</h2>
<ul>
{books.map((book) => (
<li key={book.id}>
<p><strong>Title:</strong> {book.title}</p>
<p><strong>Author:</strong> {book.author}</p>
<p><strong>Year:</strong> {book.year}</p>
</li>
))}
</ul>
</div>
);
};
export default BookList;
Output:
Book List with Functional Components
. Title: Learning React
Author: Alex Banks
Year: 2013
. Title: JavaScript: The Good Parts
Author: Douglas Crockford
Year: 2008
. Title: C Programming Language
Author: Robert C. Martin
Year: 2009
. Title: ReactJS Tutorial
Author: Marijn Haverbeke
Year: 2018
Advantages of Functional Components
This component provides many advantages that make React simpler and faster. The detailed advantage is shown below in detail:
· Improve Performance: After the coming of React Hooks, this no longer uses the lifecycle methods, making the rendering faster. It is a lightweight and potent component for better performance.
· Simpler Syntax: This component uses the simple and easy syntax because it's just like JavaScript functions.
· Reusability: This component enhances the code reusability for UI logic and composable functions. It leads to more maintainable and modular code.
Disadvantages of Functional Components
Below are some disadvantages of Functional Components in React:
· No uses lifecycle methods: Functional components are not allowed for lifecycle methods; it only uses the React Hooks.
· Limited Backward Compatibility: One of the major disadvantages of this component in React is that it is used in older projects and combined with the class components to make it confusing.
When to use Functional Components?
When the developers want to make it possible as they are very simple, stateless and easier than the class components. Mainly used for handling React Hooks to manage state and also side effects.
Some of the reasons where functional components cannot be used:
· Lifecycle methods: If you want to use lifecycle methods like initiating, mounting, updating and unmounting, etc., you cannot use functional components. In this situation, you can use the class components.
· Stateful components: These components are not allowed to take their own state. It means you can update and store changes to data inside the components. With the use of class components, we manage the state.
2. Class Components
It is another way to define a component in React. It is also known as the stateful component. This component was introduced in ES6 classes in 2015. A React class extends React.Components that include render() methods to return a JSX element. Class components are more complex than the functional components. Supports lifecycle methods like mounting, updating and unmounting, etc.
1) Syntax:
import React, { Component } from "react";
class ClassComponent extends Component {
render() {
return (
<div>
<h2>Hello from Class Component!</h2>
</div>
);
}
}
export default ClassComponent;
2) Syntax: (With lifecycle methods)
import React, { Component } from "react";
class LifeCycle extends Component {
constructor(props) {
super(props);
this.state = { message: "Component is mounting..." };
}
componentDidMount() {
// called after the component is rendered
this.setState({ message: "Component Mounted!" });
}
componentWillUnmount() {
console.log("Component is being removed.");
}
render() {
return <h2>{this.state.message}</h2>;
}
}
export default LifeCycle;
Example
Code:
import React, { Component } from "react";
class AndroidInfo extends Component {
constructor(props) {
super(props);
// state initialization
this.state = {
name: "Motorola",
Model: "G85",
Year: 2024
};
}
render() {
return (
<div>
<h1>Welcome to the Class Components Example</h1>
<h2>Android Information</h2>
<p><strong>Name:</strong> {this.state.name}</p>
<p><strong>Model:</strong> {this.state.Model}</p>
<p><strong>Year:</strong> {this.state.Year}</p>
</div>
);
}
}
export default AndroidInfo;
Output:
Welcome to the Class Components Example
Android Information
Name: Motorola
Model: G85
Year: 2024
Advantages of Class Components:
This component offers many benefits that make React simpler and faster. The detailed advantage is shown below in detail:
· Instance Methods: It allows you to manage the instance methods in the class. This can help in code organisation and structuring the component codebase.
· Lifecycle Methods: Class components support lifecycle methods like mounting, updating and unmounting, etc., for better performance. It enables fetching API, event handling and other operations, etc.
Disadvantages of Class Components:
· Complexity: Class components use the lifecycle methods and this context, which makes them more complex to understand and debug as compared to functional components.
· Difficult Debugging: One of the main disadvantages of class components is that they are difficult to debug because they use many methods like componentDidUpdate, componentDidMount, etc.
When to use Class Components?
You should consider using Class Components in React in the following situations (mainly for older codebases, since modern projects prefer functional components with Hooks).
1. Working with Legacy React Code
2. Existing Lifecycle Method Implementations
3. Complex State Logic in Older Apps
4. Team Familiarity
5. Third-Party Libraries Requiring Class Components
Difference between functional components and class components:
Features
Functional Components
Class Components
Definition
It's a simple JavaScript function that returns JSX.
It includes React.component methods to render() JSX elements.
Code Simplicity
It uses short and clean syntax.
It uses complex syntax.
Lifecycle Methods
Does not use lifecycle methods; only uses Hooks.
It uses lifecycle methods and does not use Hooks.
Performance
High performance
Slower performance
Conclusion
This article provides a deeper understanding of React components from basic to advance. React components are the building blocks of ReactJS as everything in React works as a component. Both functional and class components help to create single-page applications, reusable components and also user interfaces. Class components are used in older projects, but functional components are used to make modern projects.
I recommend that you learn ReactJS from the Tpoint tech website, as it provides React.js tutorials, interview questions, and all its related topics in easy language.