What is Components in react

In React, components are the building blocks of any React application. They are reusable, self-contained pieces of code that represent a part of the user interface (UI). Components can be thought of as JavaScript functions or classes that accept inputs (called “props”) and return React elements that describe how a section of the UI should appear.

Types of Components in React

  1. Functional Components
  2. Class Components

1. Functional Components

Functional components are simpler and are typically used when you don’t need to manage state or lifecycle methods. They are written as JavaScript functions that accept props as an argument and return React elements.

Example: Functional Component

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

2. Class Components

Class components are more feature-rich and can hold and manage state, as well as have access to lifecycle methods. They are written using ES6 class syntax.

Example: Class Component

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

Key Concepts

1. Props

Props (short for “properties”) are read-only inputs to components. They allow data to be passed from one component to another and are used to configure a component’s behavior.

Example: Using Props

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

<Welcome name="Alice" />

2. State

State is a built-in object that allows components to create and manage their own data. State can be changed over time, usually as a result of user actions or network responses.

Example: Using State in a Class Component

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

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

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

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Example: Using State in a Functional Component with Hooks

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

function Clock() {
  const [date, setDate] = useState(new Date());

  useEffect(() => {
    const timerID = setInterval(() => setDate(new Date()), 1000);
    return () => clearInterval(timerID);
  }, []);

  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {date.toLocaleTimeString()}.</h2>
    </div>
  );
}

3. Lifecycle Methods

Lifecycle methods are special methods in class components that allow you to run code at specific points in a component’s life (e.g., when the component is mounted, updated, or unmounted).

Common Lifecycle Methods:

  • componentDidMount(): Called after the component is mounted.
  • componentDidUpdate(prevProps, prevState): Called after the component is updated.
  • componentWillUnmount(): Called just before the component is unmounted and destroyed.

4. Hooks

Hooks are a feature that allows you to use state and other React features in functional components. The most commonly used hooks are useState and useEffect.

Common Hooks:

  • useState: Allows you to add state to functional components.
  • useEffect: Performs side effects in functional components (similar to lifecycle methods in class components).

Example: useState Hook

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Example: useEffect Hook

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

function Clock() {
  const [date, setDate] = useState(new Date());

  useEffect(() => {
    const timerID = setInterval(() => setDate(new Date()), 1000);
    return () => clearInterval(timerID);
  }, []);

  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {date.toLocaleTimeString()}.</h2>
    </div>
  );
}

5. Composition

React encourages the use of composition over inheritance. This means building complex UIs by combining simpler components.

Example: Component Composition

function App() {
  return (
    <div>
      <Welcome name="Alice" />
      <Welcome name="Bob" />
      <Welcome name="Charlie" />
    </div>
  );
}

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Conclusion

Components are fundamental to React, allowing for the creation of reusable, composable, and manageable UI elements. Understanding the different types of components, how to manage state and props, lifecycle methods, and the use of hooks is essential for developing React applications effectively.

Share with