Class vs. Function components

Introduction to React Class and Functional Components:-

While developing a single-page application, a developer writes thousands of lines of code that follow the traditional DOM structure. If any changes are needed, the updation gets challenging, hence a component-based approach is introduced to overcome this issue. Components are the core building blocks of any React application. It enables us to break UI into small pieces of reusable code that can be worked on independently.

The components in a React application can be created in two ways; the Functional Component or the Class Component. We’ll be discussing the differences between these components in this article.

Class Components:-

Class based or stateful component is an ES6 class that extends class components from react library. They are called stateful components as they control how the state changes and are responsible for the implementation of the component logic. Also, they have access to all the phases of a react lifecycle method.

Syntax:-

class CheckYourAttendance extends React.Component {
    render() {
        return (
            <h1>
                Hello! I'll calculate your Attendance! {this.props.name}
            </h1>;
        )
    }
}


Functional Component:-

Functional or stateless components are the most widely used type of components having a basic syntax of JavaScript Functions. In these functional Components, the return value is a JSX code that needs to be rendered.

Syntax:-

const Mobile=()=> {
return <h2>Hi, I am a Mobile!</h2>;
}


Pointing out the differences between Class components and Functional components:-

  • The most apparent difference is the Syntax. Functional components seem easy to understand as compared to the Class components. The class components use ES6 class syntax, and extends React components with a render method that returns React elements. While, functional components with hooks are JavaScript functions that also return React elements.
  • Another difference we can point out is the State and Lifecycle Methods. Before the hooks were introduced, functional components were stateless. However, with React 16.8, you can implement states with the useState hook to create a stateful component (just like the class component).

Also, with lifecycle methods, we can use the useEffect hook with functional components to accomplish the same effect as we would with lifecycle methods such as componentDidMount, componentDidUpdate and componentWillUnmount combined with the class component.

  • A Functional component has less code as compared to the Class components, hence it enhances the code readability.

Conclusion:-

The introduction of hooks has erased all the capability gaps between the Functional components and Class components. The functional components being more developer friendly, has been a more preferred choice.

Parv Saxena

Parv Saxena