Home Blog Class Components vs. Functional Components in React: Everything You Need To Know
Class Components vs. Functional Components in React: Everything You Need To Know

Class Components vs. Functional Components in React: Everything You Need To Know

Developers typically write more than a thousand lines of code that adhere to the conventional DOM structure when creating a single-page application. A component-based strategy is provided to solve this problem if any changes are required that make updating difficult. A logical group of code, known as a component, is used in this technique to partition the entire application into smaller, more manageable pieces.

React Component is compared to a wall's bricks. It greatly simplifies the process of UI creation. The final user interface will depend on the components used, which will all combine into a parent component.

React's primary functionality is provided by Components, reusable and self-contained pieces of code. Although components work independently and produce HTML, they are similar to Javascript functions.

React Component: What Is It?

While the React developer team added more features like libraries or coding tools, React components still have structure.

For building UI components, React provided two different sorts of components. The developer's preference is the only factor determining which Component is used; both offer comparable features.

The actual circumstance was that just Class components were the only practical choice to build a complex app with React, which is where we may significantly diverge from the preceding sentence by illustrating the difference.

The reason for this is that class components are used. We have many usability features, but functional components do not offer this option.

However, React v.16.8 was made available; it included an update designed to advance development levels. React supplied Hooks for useful components in this version.

Hooks allowed complicated apps to be written using simple functions as React components.

Also Read : React vs React Native: An in-depth Tabular Comparison


Ready to build your dream a​pp? Contact us for expert mobile app development. Contact Us


Let's explore the characteristics of Class and Functional Components at this moment. 

What Exactly Is A Class Component?

A normal ES6 class that extends the component class of the React library is the class component, a stateful/container component.

As a result of its control over state changes and the way the component logic is implemented, it is known as a stateful component. In addition, they have access to every stage of a React lifecycle method.

Before the introduction of React Hooks, the class component was the only way to build a dynamic, reusable component because it allowed us access to all React features and lifecycle methods.

Let's build a specific Counter component that enables users to increase or decrease a number to explain how to use the class component. Our example below will also demonstrate some of the lifecycle methods.

What Exactly Is A Class Component?
// demonstrating a Class component
class Counter extends React.Component {
     constructor(props) {
       super(props);
       this.state = { count: 0 };
     }
    
     componentDidMount() {
       this.setState({ count: this.state.count + 1 });
     }
    
    handleIncrement = () => {
       this.setState({ count: this.state.count + 1 });
     };
    
    handleDecrement = () => {
       this.setState({ count: this.state.count - 1 });
    };

     render() {
       return (
         <div className="counter">
           <h1 className="count">{this.state.count}</h1>
    
           <button type="button" onClick={this.handleIncrement}>
             Increment
           </button>
           <button type="button" onClick={this.handleDecrement}>
             Decrement
           </button>
         </div>
       );
     }
}

export default Counter;


For the Component mentioned above, since we don't want the count to begin at 0, we use the function Object() for setting the initial state and the lifecycle method componentDidMount() for setting the state from 0 to 1 after mounting the Component.

If you use the example in real-time right now, you'll see that the counts 0 and 1 are presented right after one another.

When the Component is first shown, it will quickly display the initial state's count of 0, but once the Component is mounted, the componentDidMount function will execute to set a new count state of 1.

Additionally, we add two features to the Component (handleIncrement() and handleDecrement()) that cause the counter to be incremented and decremented when the user hits one of the buttons.

What Exactly Is A Functional Component?

JavaScript functions serve as functional components. There are two methods for making them. Using the function keyword is the first method:

What Exactly Is A Functional Component?
function MyComponent(props) {
  return (
    <div>
      <p>Hello, World</p>
      <p>Have a nice day!</p>
    </div>
  );
}


Creating functional components is also possible using the syntax of the arrow function:

What Exactly Is A Functional Component?
const MyComponent = (props) => {
  return (
    <div>
   <React.Fragment>
       <p>Hello, World</p>
       <p>Have a nice day!</p>
   <React.Fragment>
     </div>
  );
}


The output of functional components is a single HTML element. Wrapping them in the topmost <div> element will allow you to return additional elements.

React.Fragment is a built-in element that may be used to do the same task. This is how it appears:

What Exactly Is A Functional Component?
const MyComponent = (props) => {
  return (
    <React.Fragment>
      <p>Hello, World</p>
      <p>Have a nice day!</p>
    </React.Fragment>
  );
}

React handles React. Fragment imitates a single HTML element (like <div>), but it doesn't render the element; therefore, it doesn't add to the DOM.

Despite having the word "component" in their name, functional components are independent of React. Component object.

Functional components are JavaScript functions that leverage React hooks to offer the same functionality as class components. Because the functions are built with just one prop object argument and return React elements, we refer to them as components.

Although it is not mandatory, the name of a JavaScript function can begin with a lowercase letter. However, the names of functional components must start with an uppercase letter.

Since they aren't class objects and don't keep state, functional components are also known as stateless components. Functional components are capable of returning HTML and accepting props as arguments.

Functional Components vs. Class Components: Differences

We discuss each distinction between class components and functional components in detail.

1. Rendering JSX or Render Function

The syntax is the first thing that stands out as being fundamentally different.

Simply put, a functional component is a Javascript function that returns JSX. On the other hand, a class component is a Javascript class that extends React.Component class with a render method.

Let's use examples to grasp each of them better.

Rendering JSX or Render Function
const FunctionalComponent = () => {
 return <h1>Hello, Welcome to React world</h1>;
};

The arrow function of ES6 was used in the aforementioned functional component example.

The snippet of code above shows that a functional component is nothing more than a Javascript function that returns the JSX code.

A functional component example without using arrow functions is also shown below.

Rendering JSX or Render Function
const FunctionalComponent(){
  return (<h1>Welcome to React world</h1>);
};

This is the fundamental syntax used to define functional components in React; let's move on to the syntax used to define class components.

By building a precise Javascript class and extending it with React.Component, we can specify the class components in React.

In the sample code snippet below, we demonstrate how to define the class component in React.

Rendering JSX or Render Function
import React, {Component} from "react"
class ClassComponent extends Component{
    render(){
        return(<h1>Welcome to the React world</h1>)
    }
}

This is how React defines class components. We trust that you now understand how to construct functional and class components in React.

2. Lifecycle Methods

Each Component in React contains several lifecycle methods, which allow you to run code at specific points in the process.

Lifecycle Methods in a Class Component

Lifecycle Methods in a Class Component
class Clock extends React.Component {
 constructor(props) {
   super(props);
   this.state = {date: new Date()};
 }

 componentDidMount() {
   this.timerID = setInterval(
     () => this.tick(),
     1000
   );
 }

 componentWillUnmount() {
   clearInterval(this.timerID);
 }

 tick() {
   this.setState({
     date: new Date()
   });
 }

 render() {
   return (
     <div>
       <h1>Hello, world!</h1>
       <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
     </div>
   );
 }
}

ReactDOM.render(
 <Clock />,
 document.getElementById('root')
);

Lifecycle Hook Methods in a Functional Component

Using the useEffect hook, we changed the clock class component above into a functional component.

To clean up, the useEffect return method is used.

Lifecycle Hook Methods in a Functional Component
function Clock(props) {
 const [date, setDate] = React.useState(new Date());

 React.useEffect(() => {
   var timerID = setInterval(() => tick(), 1000);
  
   return function cleanup() {
     clearInterval(timerID);
   };
 });
  
 function tick() {
   setDate(new Date());
 }

 return (
   <div>
     <h1>Hello, world!</h1>
     <h2>It is {date.toLocaleTimeString()}.</h2>
   </div>
 );
}

ReactDOM.render(
 <Clock />,
 document.getElementById('root')
);

Due to the use of the same hook for all lifecycle methods, the functional component useEffect is unclear. We can directly utilize the methods componentDidMount, componentWillUnmount, etc., from the class component.

3. Passing Props

One of the key ideas in the realm of React is passing props. Let's look at how React's functional and class components can pass props.

Consider the scenario below when we are sending the name "Robert" as props.

Passing Props
const FunctionalComponent = ({ name }) => {
    return <h1>Hello, { name }</h1>;
   };

We are utilizing destructuring here, but you may also use it as shown below.

Passing Props
const FunctionalComponent = (props) => {
    return <h1>Hello, {props.name}</h1>;
};

Using this syntax, you must extract the name by using the props.name syntax.

This is the method for passing props in React's functional Component.

The syntax for passing props in the class component in React is shown below.

Passing Props
class ClassComponent extends Component{
    render(){
        const { name } = this.props;
        return(
                <h1>Welcome to the React world, {name}</h1>)
    }
}

Because it is a class, whenever we use the class-based syntax, we must refer to the props using this keyword and use destructuring to retrieve the name present inside the props.

4. Accessing Components Children

The special children prop is utilized to access the Component inside content or a component like <Layout>inside content</Layout>.

Class Component

this.props.children is used for class components.

Accessing Components Children
class Layout extends React.Component {
 render() {
  return(
     <div>
       <h1>Hello {this.props.name}!</h1>
       <div>{this.props.children}</div>
     </div>
    );
 }
}

const element = <Layout name="World">This is layout content</Layout>;
ReactDOM.render(
 element,
 document.getElementById('root')
);

Functional Component

To access the content for children, props.children are used in functional components.

Accessing Components Children
function Layout(props) {
 return(
   <div>
     <h1>Hello {props.name}!</h1>
     <div>{props.children}</div>
   </div>
 );
}

const element = <Layout name="World">This is layout content</Layout>;
ReactDOM.render(
 element,
 document.getElementById('root')
);

Both make use of the same props.children to gain access to the component children. In addition, we must use the keyword this.

5. Handling State

One of the critical ideas of the React project is the concept of state. If you have been using React since its inception, you know that the only practical choice for a class component was to handle state.

However, React Hook useState was introduced in version 16.8 and later to let programmers and developers write and use state in the functional Component.

Let's examine useState, or how to handle state in a React functional component, using a straightforward counter that starts at 0, and one click on the button increases the counter by 1.

In React functional components, handling state is done in this manner

Handling State
const MyFunctionalComponent = () => {
    const[count, setCount] = useState(0);
    return(
        <div>
            <p>count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Click</button>
        </div>
    );
}

Let's examine how we can manage states in the class component

manage states in the class component
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>
   );
 }
}

This is the crucial distinction between how the state is used in functional and class components. From the perspective of a newbie, these are the fundamental distinctions.

6. Higher-Order Components

A higher-order component (HOC) is a more advanced React technique for reusing component logic. Because HOC is a pure function, it can only return a new component.

HOC with Class Component

Higher Order Components
function classHOC(WrappedComponent) {
 return class extends React.Component{
   render() {
     return <WrappedComponent {...this.props}/>;
   }
 }
}

const Hello = ({ name }) => <h1>Hello {name}!</h1>;
const NewComponent = classHOC(Hello);

const element = <NewComponent name="World" />;
ReactDOM.render(
 element,
 document.getElementById('root')
);

HOC with Functional Component

Higher Order Components
function functionalHOC(WrappedComponent) {
 return (props) => {
   return <WrappedComponent {...props}/>;
 }
}

const Hello = ({ name }) => <h1>Hello {name}!</h1>;
const NewComponent = functionalHOC(Hello);

const element = <NewComponent name="World" />;
ReactDOM.render(
 element,
 document.getElementById('root')
);

The JavaScript function should be used to build HOC (classHOC, functionalHOC). In the render method, avoid using HOCs. A class or functional components can be used inside the function.

 Get ahead in mobile app development! Subscribe now for expert insights and updates.

Conclusion

Although both approaches have advantages and disadvantages, we want to conclude that functional components will soon replace React.

As we saw in the instances, a functional component is stated more briefly and plainly, facilitating its development, comprehension, and testing.

With so many uses of this, class components might often be unclear. This clutter may be readily avoided using functional components to keep things clean.

It's also important to note that the React team enables more functional components to replace or outperform class components with React hooks.

In addition, the React team previously stated that they would reduce the number of checks and memory allocations in functional components to improve efficiency.

As encouraging as it may sound, new hooks for functional components like useState or use Effect have been added, with the assurance that they won't replace class components.

There is no need to transfer over the existing projects that use class components to the complete rewrite with functional components so that they may remain consistent. The team aims to use functional components with hooks in newer cases gradually.

Again, React supports a wide variety of legitimate code practices. However, we favor using functional components instead of class components for the above reasons. We hope this blog has given you a better understanding of contemporary React.


Still have questions? Reach out to our React experts for personalized guidance. Contact Us


In comparison to class components, functional components are thought to perform better. It should be noted that a React functional element is a straightforward object with the attributes type (string) and props (object). React only needs to call the function and pass props to render such a component.

Although the class component can be stateful or stateless, the functional Component is always stateless. Stateful and stateless components have a variety of different names.

Stateful applications need underlying storage, whereas stateless applications don't "store" data. This is the main distinction between stateful and stateless applications. Stateful programs like those used by Cassandra, MongoDB, and MySQL databases all need persistent storage that can withstand service restarts.

There's a minor feature from class-based components with no out-of-the-box function equivalent when building functional components in React. This is referred to as a constructor.

Before mounting the Component in a React component, the constructor is called. The super(props) method must be called before any other statements in the constructor of a React component. If you do not call the super(props) method, this. Undefined props can cause bugs in the constructor.

Leave a Comment

Your email address will not be published.

Submit
Your comment is under review by our moderation team.