Difference between Functional based and Class based Components

Difference between Functional based and Class based Components

Table of contents

No heading

No headings in the article.

  1. Syntax: Functional components are declared as functions, while class-based components are declared as classes.

  2. State management: Class-based components can have state, which is managed through the this.state object and can be updated using the this.setState() method. Functional components can't have state, but can use the useState() hook to manage local state.

  3. Lifecycle methods: Class-based components have lifecycle methods such as componentDidMount(), componentDidUpdate(), and componentWillUnmount(), which can be used to execute code at specific points during the component's lifecycle. Functional components can use the useEffect() hook to achieve similar functionality.

  4. Performance: Functional components are generally faster than class-based components because they have less overhead and are easier for React to optimize.

  5. Code clarity: Functional components are often more concise and easier to read than class-based components.

  6. Default props: Class-based components can define default props using the defaultProps property, while functional components use the defaultProps argument.

  7. Refs: Class-based components can use the createRef() method to create a reference to a DOM element, while functional components can use the useRef() hook.

  8. Context: Class-based components can access context using the this.context property, while functional components can use the useContext() hook.

  9. Error handling: Class-based components can define an errorBoundary to catch errors in child components, while functional components can use the useErrorHandler() hook.

  10. Ex-

    Functional Component:

    import React from 'react';
    
    function HelloWorld(props) {
      return (
        <div>
          <h1>Hello, {props.name}!</h1>
        </div>
      );
    }
    
    export default HelloWorld;
    

    Class-based Component:

    import React from 'react';
    
    class HelloWorld extends Components {
      render() {
        return (
          <div>
            <h1>Hello, {this.props.name}!</h1>
          </div>
        );
      }
    }
    
    export default HelloWorld;
    

    Both components render a simple "Hello, {name}!" message where name is a prop passed in from the parent component. The functional component is declared as a function that returns a React element, while the class-based component extends React.Component and overrides the render() method to return a React element.

Overall, functional components have become more popular in recent years because they are simpler, more concise, and easier to test. However, class components are still used in some cases, particularly when you need to manage complex state or use lifecycle methods that are not available in functional components.