Functional Components vs. Class Components in React.js

Posted By :Rajat Soni |29th June 2021

 

There are two approaches to write a React component in React. One uses a function, whereas the other makes use of a class. Functional components are becoming increasingly popular in recent years.

 

Rendering JSX

 

The first point to note is that the syntax is different. A functional component is simply a JavaScript function that returns JSX, as their names suggest. A class component is a React-extended JavaScript class. A render method is a component that has a render method. Let's look at a simple scenario.

 

import React from "react";

const FunctionalComponent = () => {

return <h1>Hello, world</h1>;

};

 

A functional component, as you can see, is a JSX-returning function.
On the other hand, while creating a class component, you must create one that implements React.


Component. Inside the render method, the JSX to render will be returned.

 

import React, { Component } from "react";

class ClassComponent extends Component {

render() {

return <h1>Hello, world</h1>;

}

}

 

Passing props

 

Passing props might be perplexing, so let's take a look at how they're written in class and what are their functional components. Let's pretend we're passing props for the name "Rajat," as seen below.

 

<Component name="Rajat" />

const FunctionalComponent = ({ name }) => {

return <h1>Hello, {name}</h1>;

};

 

Props are passed as an argument to a function within a functional component. Props are given as an argument to a function within a functional component. It's worth noting that we're utilizing destructuring in this case. We can also write it without it if we choose to.

 

const FunctionalComponent = (props) => {

return <h1>Hello, {props.name}</h1>;

};

 

In this case, you have to use props.name instead of name.

 

class ClassComponent extends React.Component {

render() {

const { name } = this.props;

return <h1>Hello, { name }</h1>;

}

}

 

It would be best if you used this to refer to props because it is a class. Destructuring can also be used to get names inside props when using class-based components.

 

Handling state

 

Until recently, handling state in a class component was a bit complicated, but with React 16.8, React Hook useState was introduced, allowing developers to construct stateful functional components.

 

Handling state in functional components

 

const FunctionalComponent = () => {

const [count, setCount] = React.useState(0);

return (

<div>

<p>count: {count}</p>

<button onClick={() => setCount(count + 1)}>Click</button>

</div>

);

};

 

To use state variables in a functional component, we must use the useState Hook, which accepts an initial state as an input. We'll start with 0 clicks in this scenario, so the initial state of the count will be 0.

 

Of course, you can have a broader range of beginning states, such as null, string, or even object - any type supported by JavaScript! On the left, useState returns the current state as well as a function.

 

Handling state in class components

 

class ClassComponent extends React.Component {

constructor(props) {

super(props);

this.state = {

count: 0

};

}

render() {

return (

<div>

<p>count: {this.state.count} times</p>

<button onClick={() => this.setState({ count: this.state.count + 1 })}>

Click

</button>

</div>

);

}}

 

The concept remains the same, but the state is handled differently in a class component. To begin, we must comprehend the significance of React.


Component function Object() { [native code] }.


The official documentation provides the following definition:
"Before a React component is mounted, its function Object() { [native code] } is invoked. Before calling any other methods in the function Object() { [native code] } of a React. Component subclass, should be called super(props).

 

onClick={() =>

this.setState((state) => {

return { count: state.count + 1 };

})

}

 

Lifecycle Methods

 

Finally, let us discuss lifecycles. Please wait a minute; we're nearly there! As you may be aware, lifecycles play a crucial part in rendering timing. If you're migrating from class components to functional components, you're probably thinking about what may replace lifecycle methods in a class component like componentDidMount(). 

Yes, there is a hook that is ideal for the purists.

 

On Mounting (componentDidMount)

 

Component of the lifecycle method DidMount is called immediately after the first render is finished. ComponentWillMount used to happen before the first render, but it's now considered obsolete and isn't encouraged for use in subsequent React versions.

 

const FunctionalComponent = () => {

React.useEffect(() => {

console.log("Hello");

}, []);

return <h1>Hello, World</h1>;

};

 

We utilize the useEffect hook with the second argument of [ to replace componentDidMount. The useState hook's second argument is usually an array of state(s) that change and useEffect will only be invoked on these changes. However, if the array is empty, as in this case, it will only be called once during mounting. This is an excellent alternative to componentDidMount.

 

class ClassComponent extends React.Component {

componentDidMount() {

console.log("Hello");

}

render() {

return <h1>Hello, World</h1>;

}

}

 

ComponentDidMount is a lifecycle method that is called once after the first render, and it does the same thing here.

 

On Unmounting (componentWillUnmount)

 

const FunctionalComponent = () => {

React.useEffect(() => {

return () => {

console.log("Bye");

};

}, []);

return <h1>Bye, World</h1>;

};

 

I'm pleased to inform you that we may also use a useState hook for unmounting. However, be aware that the syntax is slightly different. Inside the useEffect function, you must return a function that runs on unmounting. This is especially important when you need to clean up subscriptions, such as with the clearInterval function, because otherwise, a more extensive project could suffer from a severe memory leak.

 

class ClassComponent extends React.Component {

componentWillUnmount() {

console.log("Bye");

}

render() {

return <h1>Bye, World</h1>;

}}

 

Conclusion

 

Both methods have advantages and disadvantages, but I believe functional components will take over modern React shortly.

As seen in the examples, a functional component is written shorter and more straightforward, making it easier to design, comprehend, and test.

 

Class components can also be confusing with so many uses of "this."

 

Using functional components can help you avoid "this" type of clutter and keep things tidy.

It's also worth noting that the React team is promoting more React hooks for functional components, which can replace or even augment class components.

 

In React, there are numerous valid coding styles. However, for the reasons stated above, I prefer to use functional components over class components. I hope this blog has given you a better understanding of the current React. 

 


About Author

Rajat Soni

Rajat Soni is working as a Frontend Developer with approx 2+ years of experience and holding certification in the domain. He is skilled in AWS services ( EC2, S3 bucket, Open search), HTML/CSS, ReactJS, Client Management, Solution Architect and many more related technologies. He has been a part many successful projects namely Konfer project, where he has migrated the project from Angular js to Angular 12 , Virgin Media Project, I-Infinity project & many more along with leading the team to handling the project end to end.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us