What is Class Based Components and Functional Based Components in React js

  • In React, there are two main types of components: class-based components and functional components.
Class-based components
  • Class-based components are defined using ES6 classes and extend the React.Component class. They have access to state and lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount. Here is an example of a class-based component:

import React, { Component } from 'react';

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
    }

    componentDidMount() {
        console.log('Component mounted');
    }

    componentDidUpdate() {
        console.log('Component updated');
    }

    componentWillUnmount() {
        console.log('Component will unmount');
    }

    render() {
        return (
            <div>
                <p>You clicked {this.state.count} times</p>
                <button onClick={() => this.setState({ count: this.state.count + 1 })}>Click me</button>
            </div>
        );
    }
}

Functional components
  • Functional components, on the other hand, are defined using regular JavaScript functions. They do not have access to state or lifecycle methods and are primarily used to render UI elements. However, with the introduction of hooks in React, functional components can now have state and use lifecycle methods. Here is an example of a functional component:

import React, { useState, useEffect } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log('Component mounted or updated');
    });

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
    );
}
  • In this example, we define a functional component called Example using a regular JavaScript function. We use the useState hook to define a state variable called count and a function called setCount that can be used to update the count. We also use the useEffect hook to perform side effects when the component is mounted or updated.
  • Overall, both class-based components and functional components can be used to create UI elements in React, but the use of hooks has made functional components more powerful and easier to use for managing state and performing side effects.

No comments:

Post a Comment