What are the Components in React JS?

In React, a component is a fundamental building block of the user interface. Components are reusable, self-contained pieces of code that encapsulate logic and rendering for a portion of the UI. They enable you to build complex UIs from small, isolated, and reusable pieces of code.

Types of Components

There are two main types of components in React:

  1. Functional Components: Functional components are simple JavaScript functions that take props as an argument and return React elements. They are often used for components that do not require state management or lifecycle methods.
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Class Components: Class components are ES6 classes that extend from React.Component and must define a render method that returns React elements. They can hold and manage their own state and have access to lifecycle methods.

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Props and State

  • Props: Props (short for properties) are read-only inputs passed from a parent component to a child component. They allow data to flow from the parent to the child and are accessible via this.props in class components or as function arguments in functional components.
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

// Usage
<Greeting name="John" />

State: State is a built-in object that allows components to hold and manage their own data. Unlike props, the state is mutable and can be changed with the setState method in class components or with the useState hook in functional components.

// Class component with state
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}
// Functional component with state
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>
  );
}

Lifecycle Methods

Class components have lifecycle methods that allow you to execute code at specific points in a component's lifecycle. Some common lifecycle methods include:

  • `componentDidMount`: Called after the component is mounted (inserted into the DOM).
  • `componentDidUpdate`: Called after the component updates (when props or state change).
  • `componentWillUnmount`: Called before the component is unmounted (removed from the DOM).
class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentDidUpdate() {
    console.log(`Timer updated: ${this.state.seconds}`);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  tick() {
    this.setState({ seconds: this.state.seconds + 1 });
  }

  render() {
    return <div>Seconds: {this.state.seconds}</div>;
  }
}

Hooks in Functional Components

Hooks are functions that let you use state and other React features in functional components. Some commonly used hooks are:

  • `useState`: Adds state to a functional component.
  • `useEffect`: Performs side effects in functional components, similar to lifecycle methods in class components.
  • `useContext`, `useReducer`, `useRef`, etc.
import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => setSeconds(seconds => seconds + 1), 1000);
    return () => clearInterval(interval); // Cleanup on unmount
  }, []);

  return <div>Seconds: {seconds}</div>;
}

Composition

Components can be composed together to build complex UIs. A component can contain other components as children.

function App() {
  return (
    <div>
      <Header />
      <Content />
      <Footer />
    </div>
  );
}

Conclusion

Components are the cornerstone of React applications, enabling modular, reusable, and maintainable code. Understanding how to create and manage components, handle state and props, and utilize lifecycle methods and hooks is essential for building robust React applications.

Further, if you have any questions, please visit our website, Gurulabs Website Design Agency.