20 Feb 2024




Beginner

The two main types of components in ReactJS are:

  1. Functional Components: Functional components are JavaScript functions that return React elements. They are primarily used for presenting UI elements based on props (input data) and are simpler and more concise compared to class components. With the introduction of hooks in React, functional components can now manage state and lifecycle methods, making them more powerful and versatile.

    Example of Functional Component:

    import React, { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }
    
    export default Counter;
    

    In the above example, useState hook is used to declare a state variable count and a function setCount to update it.

  2. Class Components: Class components are JavaScript classes that extend from React.Component and have their own state and lifecycle methods. Historically, class components were the primary way of building components in React. They still play a role in existing codebases, but functional components with hooks have largely replaced them in modern React development due to their simplicity and flexibility.

    Example of Class Component:

    import React, { Component } from 'react';
    
    class Counter extends Component {
      constructor(props) {
        super(props);
        this.state = {
          count: 0
        };
        this.incrementCount = this.incrementCount.bind(this);
      }
    
      incrementCount() {
        this.setState({ count: this.state.count + 1 });
      }
    
      render() {
        return (
          <div>
            <p>Count: {this.state.count}</p>
            <button onClick={this.incrementCount}>Increment</button>
          </div>
        );
      }
    }
    
    export default Counter;
    

    In this class component, count is initialized in the constructor using this.state. The incrementCount method is used to update the count state when the button is clicked. It's important to bind this to incrementCount in the constructor to ensure it refers to the component instance.