1. Types of Components in React.js
In React.js, components are the building blocks of a user interface. Each component represents a piece of the UI, which can be reused and managed independently. React components can be broadly categorized into two main types based on how they are defined and their behavior: Functional Components and Class Components. Let's explore each type and its characteristics.
2. Functional Components
Functional components, also known as stateless components, are the simplest form of React components. They are JavaScript functions that accept props (inputs) as arguments and return React elements, typically JSX, to describe the UI.
Key Characteristics:
useEffect
, functional components can handle lifecycle events such as mounting and unmounting.Example:
function Greeting(props) {
return Hello, {props.name}!
;
}
In the example above, Greeting
is a functional component that accepts props
and returns a JSX element that displays a greeting message.
3. Using Hooks in Functional Components:
With the addition of hooks, functional components can now handle state and lifecycle methods.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
You clicked {count} times
);
}
In this example, useState
is used to manage the component's state inside the functional component.
4. Class Components
Class components are a more traditional way of writing React components. They are ES6 classes that extend from React.Component
and include methods for rendering UI and managing state
Key Characteristics:
componentDidMount
, componentDidUpdate
, and componentWillUnmount
, which provide more control over the component's behavior at different stages of its lifecycle.Example:
import React, { Component } from 'react';
class Greeting extends Component {
render() {
return Hello, {this.props.name}!
;
}
}