20 Feb 2024
The two main types of components in ReactJS are:
-
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,
useStatehook is used to declare a state variablecountand a functionsetCountto update it. -
Class Components: Class components are JavaScript classes that extend from
React.Componentand 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,
countis initialized in the constructor usingthis.state. TheincrementCountmethod is used to update the count state when the button is clicked. It's important to bindthistoincrementCountin the constructor to ensure it refers to the component instance.