Choosing between Functional and Class Components in ReactJS Applications - Netwoven

Choosing between Functional and Class Components in ReactJS Applications

By Debopoma Chaudhury  •  November 16, 2021  •  1660 Views

Choosing between Functional and Class Components in ReactJS Applications

Introduction:

The choice between Functional and Class components was easy until Feb 2019. Functional components were stateless and Class components stateful. If there was a project that does not require maintenance of state or different usages of page life cycle methods, one would opt for Functional components for its simplicity, else the choice was Class components. Since most complex applications required state maintenance, Class components became extremely popular. But then ‘hooks’ were introduced in Functional components that added the ability of state and page lifecycle management. Gradually, Functional components were getting used more. Even behemoths such as Facebook, Netflix, Instagram are now using React Functional components, which begs the question, ‘Should we shift from Class to Functional components?

Functional Components:

Creating a Functional component

Functional components are simple, short and easy to write. Those who are used to object-oriented programming may find the syntax a little difficult to adapt initially but once they get a hold of it, it saves loads of lines of code. Below is a sample code-

const FunctionalComponent = (props) => {
cons[counter , setCounter]=useState(0);
 
 const increaseUser=()>{
     setCounter(counter+1);
 }

 React.useEffect(() => {
   return () => {
console.log("Done");
   };
 }, []);
 return <div>
            <h1>Welcome User:{props.username} </h1>
            <h3>User Count: </h3>
          <h2>{counter}</h2>
            <button onClick={increaseUser}>Add</button>
        </div>;
};

In the sample above, this Functional component gets user details as input and prints the user-name. Also, this has an additional button that increments the user counter by using useState. So here props and states are taken care of. The useEffect takes care of page lifecycle methods. The sample above has a return, so this is called on component unmount page event. Without the return keyword in useEffect, it represents both components mount and component update events.

Pros of Functional Components:
  • Functional components are simple functions that are easy to read. Code maintenances wise it is easy and understandable even when you refer after a long time.
  • There is no requirement for constructor and individual page life cycle methods. State and lifecycle handling is easily done using “hooks” like useState and useEffect.
  • There is no need to be concerned about the ‘this’ keyword which creates confusion between page scope, event scope, etc.
  • Also function binding, constructors are not required for component initialization.
  • Decoupling is easy in Functional components. It is extremely easy to identify and differentiate UI and logic, making the components effectively reusable.
  • There is scope for performance improvement making its performance better than Class components. Today the improvement is 6% but React team promises it can go up to 45%.
  • Debugging and testing are easier as these are simple JavaScript functions.
Cons of Functional Components:
  • In the versions before React 16, the hooks were not there, and state management was not possible in Functional components. So earlier versions cannot support state.
  • People who are used to object-oriented programming format, find using Class components much easier to pick up. The syntax is a little difficult to understand for those who are used to the Class model.
  • Stateful logic should ideally be separated out from Functional components and hence not making it reusable as a complete unit.
  • For complex components, code is harder to understand due to decoupling.
  • For complex state management, Redux might be required to support Functional components.

Class Components:

Creating a Class component

Class components in React are very similar to object-oriented programming languages. People used to C#, Java can very easily pick up this coding structure having constructors, page life cycle methods, etc. Below is a sample code-

export Class ClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
    this.increaseUser = this.increaseUser.bind(this);
  }
  componentWillUnmount() {
    console.log("Done");
  }

  increaseUser() {
    this.setState({counter: this.state.counter + 1});
  }

  render() {
    return (
       <div>
            <h1>Welcome User:{this.props.username} </h1>
            <h3>User Count: </h3>
          <h2>{this.state.counter}</h2>
            <button onClick={this.increaseUser}>Add</button>
        </div>
    );
  }
}

In this sample, the Class component gets user details as input and prints username. Also, this has an add button that increments the user counter by 1 using setState. The component is initialized in the constructer and the other used function increaseUser here is bound in the constructor. ComponentWillUnmount event is called for performing the action on unloading the component. So, both the code snippets provided following the different component structures here give the same output, but the syntax and structure are different. The number of lines of code is lesser in Functional component and simpler.

Pros of Class Components:
  • Till 2019, Class Components was the only means of state management and life cycle management in React and hence most complex projects used it
  • The coding format is very easy to learn if you are acquainted with any object-oriented programming language like C#, Java.
  • Stateful logic and UI can be maintained within the same component, keeping it coupled
  • Complex designs can be easily achieved by mimicking object-oriented concepts
  • Class components are sufficient for complex state management, there is no requirement of Redux.
Cons of Class Components:
  • Code maintenance is more complex than Functional components. The number of lines of code is more and readability is more complex
  • Performance of Functional components is better now and will further improve, making performance a bottleneck for Class components in the future
  • Decoupling is not easy in Class components. All UI and stateful logic are maintained in the same component making reusability not as flexible as Functional components.
  • Testing, simulation and debugging are more complex than Functional components.

Functional components or Class components- Which one to Choose when architecting a project?

The choice is still a difficult one. The trend is to move towards Functional components and yet React has no plans to deprecate Class components as it is also a recommended approach. React forum supports both models, and it is at the discretion of an individual to choose between them.

People who have been developing complex applications for years now in React have become extremely comfortable with the Class component model and it is difficult to move out of this model when it is a tried and tested one. But going with the flow, extensive studies suggest that in later versions, there might be a significant improvement in performance with use of Functional components, as well as code maintenance would be quite easier. It is suggested that, as recommended now by experts, to try the Functional components with hooks in any one of the projects. Unless you try it out, you will not understand the difference, as initially syntax change is a big change one needs to overcome. Only upon overcoming that, one can understand that Functional components is simpler to code, number of lines is lesser, it is cleaner, easier to maintain and improves performance. Highly complex projects with coupled modules are not ideal for Functional components, so you must choose wisely based on the project complexity, but you should try the Functional components.

Conclusion:

Since most large organizations are going for ‘hooks’ and Functional components, it is worth trying to experience its benefits and judge with one’s own experience as to which one is better. The only challenge is to adapt to the significant syntax changes and decide to use it in less complex projects where interdependency between modules is less. Both Functional and Class components will keep ruling the React world and one has to decide per project basis as to which one to choose.

Leave a comment

Your email address will not be published. Required fields are marked *

Dublin Chamber of Commerce
Microsoft Partner
Microsoft Partner
Microsoft Partner
Microsoft Partner
Microsoft Partner
Microsoft Partner
Microsoft Fast Track
Microsoft Partner
Microsoft Fabric
MISA
MISA
Unravel The Complex
Stay Connected

Subscribe and receive the latest insights

Netwoven Inc. - Microsoft Solutions Partner

Get involved by tagging Netwoven experiences using our official hashtag #UnravelTheComplex