In React, we can create components in two ways functional components and class components. But both methods have their own distinct characteristics due to which many developers find it difficult to decide when to use which method. So, in this article, we will cover everything that will help you understand why many people often prefer functional components.
Let's dive in!
Table of contents
- What is the React component?
- What is the Functional component?
- What is the Class component?
- Difference between Functional component and Class component
- Which should we use?
- Why do developers prefer Functional components over Class components?
What is the React component?
In React JS, a component is like a building block for the user interface (UI), representing a specific part of it. Essentially, all React applications are composed of these components.
Components make UI creation easier by breaking it into manageable pieces. Each piece, called a "React component," can be worked on individually and then combined with others to form the final UI.
The UI of the CodeMafias website's question page has been divided into separate components.
Components in React basically return a piece of JSX (JavaScript XML) code that describes what should be rendered on the screen.
What is the Functional component?
A function component in React is a JavaScript function that returns JSX, representing a portion of the user interface. It's a simpler way to create components compared to class components and is often used for stateless or presentational components.
There are two methods for creating functional components. The first method is to use a regular function, i.e. using a function keyword, and the second method is to use the JavaScript arrow function.
1. Functional component using the "function" keyword
function Header(props) {
return (
<h1>Hello, {props.name}</h1>
)
}
In this example, the Header function is a functional component that accepts a props object as an argument and returns a JSX element.
2. Functional component using the "arrow function" (added to a recent version of React with Hooks)
const Header = ({ name }) => {
return <h1>Hello, {name}</h1>;
}
In JavaScript, function names can start with lowercase letters, but in React, functional component names must start with uppercase letters to differentiate them from regular functions when working with JSX.
What is the Class component?
A class component in React is a JavaScript class that extends React.Component class. It requires a render() method to return the component's JSX. Class components can manage their own state and have lifecycle methods for handling component events.
Here is an example of a class component:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = { text: 'Hello world!' };
}
render() {
return <h1>{this.state.text}</h1>;
}
}
In this example, the Header class is a class component extending the React.Component base class. Its render method returns a JSX element.
The constructor initializes the component's state, with the super() method required to call the parent class constructor.
Functional components with hooks can replace some use cases of class components, which is considered best practice.
Class components are used for state or lifecycle methods, providing flexibility and control despite being complex and having more code than functional components.
Difference between Functional component and Class component
Functional components:
Functional components in React are created using JavaScript functions. They are usually used for components that only need to render some UI based on props supplied to them and do not need to maintain any internal state.
Syntax:
function Header(props) {
return (
<h1>Hello {props.name}</h1>
)
}
Class components:
A class component in React is essentially a JavaScript class that extends the React component. They're commonly utilized for components that require internal state management or utilize lifecycle methods.
Syntax:
class Header extends React.Component {
render() {
return (
<>
<h1>Hello{this.props.name}</h1>
</>
)
}
}
You may notice a difference in how these two components are written. Class components need a render() method, while functional components do not.
Let's compare both types of components using different examples.
1. Handling State
Previously, only class components could manage states, not functional components. However, now it's possible to manage the state of a functional component by using hooks.
For example, by using the Functional component
import React, { useState } from "react";
function Header() {
const [Number, setNumber] = useState(0);
const plus = () => {
setNumber(Number + 1);
}
const minus = () => {
setNumber(Number - 1);
}
return (
<div className="container">
<h1>Using Functional Component</h1>
<p>Counter App</p>
<p className="number">{Number}</p>
<button className="btn btn-1" onClick={plus}>+</button>
<button className="btn btn-2" onClick={minus}>-</button>
</div>
)
}
export default Header;
For example, by using the Class component
import React from "react";
class Header extends React.Component {
constructor() {
super();
this.state = { count: 0 };
this.plus = this.plus.bind(this);
this.minus = this.minus.bind(this);
}
plus() {
this.setState(
{ count: this.state.count + 1 }
);
}
minus() {
this.setState(
{ count: this.state.count - 1 }
);
}
render() {
return (
<div className="container">
<h1>Using Class Component</h1>
<p>Counter App</p>
<p className="number"> {this.state.count}</p>
<button className="btn btn-1" onClick={this.plus}> + </button>
<button className="btn btn-2" onClick={this.minus}> - </button>
</div>
)
}
}
export default Header;
As you can see in the examples of these two components, class components manage state using this.state and this.setState(), while functional components utilize hooks like useState() for state management.
2. Passing Props
For example, by using the Functional component
function Header(props) {
return <h1>Hello {props.name}</h1>
}
For example, by using the Class component
class Header extends React.Component {
render() {
const { name } = this.props;
return <h1>Hello {name}</h1>;
}
}
In the above code snippet, functional components receive props as an argument, while class components access them through the this.props object.
It's important to understand that you can pass objects, arrays, and numbers to components. You can also give functions as props, such as callback functions, which allow child components to connect with their parent components.
3. Methods of Lifecycle
For example, by using the Functional component
Functional components, which don't maintain their own state, don't come with built-in lifecycle methods like class components do. But with the useEffect hook, we can replicate some lifecycle behavior, like handling actions when a component mounts or unmounts, in a straightforward manner.
const Header = () => {
React.useEffect(() => {
return () => { console.log("World"); };
}, []);
return <h1>Hello World</h1>;
};
For example, by using the Class component
class Header extends React.Component {
componentWillUnmount() { console.log("World!"); }
render() { return <h1>Hello World</h1>; }
}
As you can see, in the class component, we use traditional lifecycle methods to manage component behavior, whereas, in the functional component, we rely on the cleanup function from the "useEffect" hook. While functional components can't directly use lifecycle methods, they can achieve similar effects using hooks.
Hooks in functional components provide a straightforward method for managing state. Hooks are only for functional components.
Which should we use?
We should use functional components in React JS because they're simpler and look like regular JavaScript functions, which makes them easier to understand for developers. With the introduction of hooks in React v16.8, functional components became even more powerful. Hooks allow us to easily incorporate lifecycle methods and manage states and effects within functional components.
Functional components are typically preferred in most scenarios due to their cleaner and more straightforward syntax. However, there are specific cases, such as error handling, where class components are still necessary because they support error-boundary lifecycle methods like static getDerivedStateFromError() or componentDidCatch().
Functional components are usually the best option, but to become a professional React developer, it is important to understand both options and select the right option based on the requirements of the project.
Why do developers prefer Functional components over Class components?
Functional components are favored over class components in ReactJS development for several reasons. Here are some of the most important ones.
Performance: Functional components are more effective than class components because they do not have the overhead of additional features such as the ability to use the "this" keyword.
Simplicity: Functional components use plain JavaScript functions, making them simpler and easier to understand compared to class components.
Lightweight Syntax: Functional components have a lighter syntax, which reduces boilerplate code and improves readability.
Hooks: React Hooks, introduced in React v16.8, work only with functional components. They allow developers to handle state and use other React features in functional components, adding to their flexibility and usefulness.
Reusability: Functional components are easier to reuse because they aren't bound by the restrictions of class components, making it simpler to support and maintain components.
Since the introduction of hooks, React has reduced the distinction between functional and class components, making it easier for developers to choose between the two. Functional components are generally preferred due to their modern and recommended approach.
Conclusion
Functional Components are simpler, like JavaScript functions, while Class Components are more complex, built with JavaScript classes. Functional Components are popular for their simplicity and versatility with Hooks, introduced in React v16.8. Hooks enable managing state and lifecycle methods in functional components. However, Class Components are still used, especially for error handling. Beginners often start with Functional Components due to their simplicity.
I hope this article has helped you better understand “Functional Component vs Class Component in React JS”. If you have any questions about this article or web development, you can ask in the question box given below and you will get the right answer ASAP.