When to use Class Component and Functional Component in React?

In React there are two ways of writing components functional components & class components so, here we’ll see when to use, which way. by comparing both on few Important key points

GraphQL has a role beyond API Query Language- being the backbone of application Integration
background Coditation

When to use Class Component and Functional Component in React?

In React there are two ways of writing components functional components & class components so, here we’ll see when to use, which way . by comparing both on few Important key points-

Rendering JSX-

In syntax, a functional component is just a plain JavaScript function that returnsJSX.

function Hello(props)

{

return (  

<div>    

<h3> Greetings of the Day! </h3>  

</div>

);

}

Aclass component is a JavaScript class that extends React.Component which has arender method.

class Hello extends React.Component {

render() {

  return (

    <div>

      <h3> Greetings of the Day! </h3>

    </div>

  );

}

}

Passing props in Component-

Inside a functional component, we arepassing props as an argument of the function.

function Name(props) {

return (

  <div>

    <h3>{props.name}</h3>

  </div>

);

}

But in a class component, you need to use `this` to refer to props.

class Name extends React.Component {

render() {

  return (

    <div>

      <h3>{this.props.name}</h3>

    </div>

  );

}

}

State Handling -

HandlingState was only possible in a class component but after React 16.8, React Hook `useState ` was introduced to allow developers to write stateful functionalcomponents.

import useState from 'react';

const Counter = () => {

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

return (

  <div>

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

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

  </div>

);

};

The constructor for a Class component is called before it is mounted. without implementing the constructor & super(props), all the state variables that you are trying to use will be undefined. Inside the constructor, we will put a state object with a state key and initial value.

class Counter extends React.Component {

constructor(props) {

  super(props);

  this.state= {

    count: 0

  };

}

render() {

  return (

    <div>

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

      <button onClick={()=>

      this.setState({ count: this.state.count +1 })}>

       Increment

      </button>

    </div>

  );

} }

Lifecycle Methods -

lifecycles play an important role in rendering time. Here we will compare the most usedLifecycle method . Which is componentDidMount that is called right after the first render completes.

class Hello extends React.Component {

componentDidMount() {

  console.log("Hello");

}

render() {

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

}

}

In replacement of `componentDidMount` , We use the useEffect hook with the secondargument of [ ]. This argument of the useState hook is an array of state thatchanges, and `useEffect` will be only called on this selected changes .


But when it’s an empty array like this example, it will be called once on mounting.

const Hello = () => {

 React.useEffect(() => {

  console.log("Hello");

}, []);

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

};

After deep comparisons here are few things to Notice -

Functional Component over Class Component

It's hard to reuse Stateful logic between Components in Class Component, if you look at a typical React application in React Dev Tools, you will likely find a “Wrapper Hell” of Components Surrounded by layers of “Providers, Consumers, Higher-Order Components, Render Props & Other Abstractions”.

Because these Patterns require to Restructure Components when you use them. Which can be cumbersome and make code harder to follow.

Whereas in Functional Components with hooks, you can extract stateful logic from a component, So it can be tested independently &reused. Hooks allows you to reuse stateful logic without changing your component hierarchy.

Use Functional Component with hooks for Performance Optimizations also to avoid Unnecessary checks & memory allocation.

Complex Components became hard to understand (completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs & inconsistencies), Class Components can encourage Unintentional Pattern that make these optimization fall back also Class Components do not minify very well, and they make hot reloading flaky & unreliable.  

whereas Functional components let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data).

Class Component over Functional Component

In Class components, the render method will be called, whenever the State of the components changes. On the other hand, the Functional components render the UI based on the Props.

After the Release of React version 16.8 , we can use all Class based Components features in the form of Hooks in Functional Components also.

So now, The only reason to use Class Components with modern React is to use Error Boundaries since there isn't any Hook introduced in replacement of it.

Conclusion :-

As per above mentioned examples here we noticed that There are pros and cons in both Component types but I would like to conclude that functional components are taking over modern React in the foreseeable future.

Want to receive update about our upcoming podcast?

Thanks for joining our newsletter.
Oops! Something went wrong.