React Components

React Components
React Components

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.


FAQs of React Components

Here are some frequently asked questions (FAQs) about React Components:

1. What are React Components?

React components are the building blocks of a React application. They allow developers to break the UI into reusable, independent pieces. Each component can manage its own state and logic, and they can be nested or composed together to create complex UIs.

2. What are the different types of React Components?

React components are generally classified into two types:

  • Functional Components: These are simple functions that return JSX and are commonly used in modern React development.
  • Class Components: These are ES6 classes that extend React.Component and include lifecycle methods. While still used, class components are being phased out in favor of functional components with hooks.

3. What is JSX in React Components?

JSX stands for JavaScript XML, and it’s a syntax extension that allows developers to write HTML-like code inside JavaScript. It’s used to define the structure of the UI inside React components.

4. What is the difference between stateful and stateless components?

  • Stateful Components: Also known as class components, they can hold and manage their own state using the state object.
  • Stateless Components: These are functional components that do not hold or manage state on their own. They simply receive data through props.

5. How do Props work in React Components?

Props (short for properties) are a way of passing data from one component to another in React. They are read-only, meaning that components receiving props cannot modify them directly. Props allow for dynamic and reusable components by passing in different values.

6. What is the difference between props and state?

  • Props are used to pass data from one component to another. They are immutable and controlled by the parent component.
  • State is a way to store and manage data within a component. Unlike props, state is mutable and can change over time through user interactions or other actions within the app.

7. How do you pass data between components in React?

Data can be passed between components using props. A parent component can pass props to child components, and data can be sent back up using callback functions.

8. What are React Hooks, and how do they relate to functional components?

Hooks are functions that allow you to use React features like state and lifecycle methods in functional components. The most commonly used hook is useState, which allows a functional component to have its own state.

9. Can a component have multiple child components?

Yes, a React component can render multiple child components by using JSX syntax. Components can be composed together, allowing for a modular and flexible UI design.

10. What are Higher-Order Components (HOCs)?

A Higher-Order Component is a function that takes a component and returns a new component. HOCs are used to add common functionality to components, such as handling authentication or tracking analytics.

11. What is the lifecycle of a React Component?

For class components, React provides several lifecycle methods that are called at different stages:

  • Mounting: componentDidMount
  • Updating: componentDidUpdate
  • Unmounting: componentWillUnmount

In functional components, React hooks such as useEffect are used to handle lifecycle events.

12. What is a Controlled Component in React?

A controlled component is a form element (like input or select) whose value is controlled by the React state. In controlled components, the form data is handled by React, and the state is updated every time the input value changes.

13. What is the purpose of key in a list of components?

The key prop is a special attribute used to help React identify which items have changed, been added, or removed in a list. Keys should be unique, and they help React optimize the re-rendering process of lists.

14. What is a Pure Component in React?

A Pure Component is a class component that implements the shouldComponentUpdate method by performing a shallow comparison of props and state. Pure components improve performance by avoiding unnecessary re-renders.

15. How do you style React Components?

React components can be styled using a variety of methods:

  • CSS Stylesheets
  • Inline styles
  • CSS Modules
  • Styled-components, a popular library for writing actual CSS syntax in JavaScript files.

These FAQs cover the fundamentals of React components, helping developers understand their role in building scalable and reusable user interfaces.


Read other awesome articles in Medium.com or in akcoding’s posts.

OR

Join us on YouTube Channel

OR Scan the QR Code to Directly open the Channel 👉

AK Coding YouTube Channel

Share with