Components in React

Learn the fundamentals of React components and how they help build scalable applications.

1. What are Components?

Components are the building blocks of any React application. They encapsulate UI logic and rendering in reusable, modular pieces.

  • Reusability: Write once and reuse across your application.
  • Encapsulation: Components manage their own state and behavior.
  • Composition: Combine components to create complex UIs.

2. Types of Components

React has two primary types of components:

  • Functional Components: Defined as functions and primarily used for rendering UI. Introduced with hooks for managing state and side effects.
  • Class Components: Defined as ES6 classes, used for stateful logic and lifecycle methods.

Example of a functional component:

function Greeting() {
    return 

Hello, World!

; }

Example of a class component:

import React, { Component } from 'react';

class Welcome extends Component {
    render() {
        return 

Welcome to React!

; } } export default Welcome;

3. Props in Components

Props (short for properties) are used to pass data from a parent component to a child component.

function UserInfo(props) {
    return 

User: {props.name}

; } function App() { return ; }

Explanation: In this example, the name prop is passed from the App component to the UserInfo component.

4. State in Class Components

State is an object that holds dynamic data for a component. It is used for interactivity and user-driven behavior.

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

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

    render() {
        return (
            

Count: {this.state.count}

); } }

Explanation: The increment method updates the count state when the button is clicked.

5. Using Functional Components with Hooks

Hooks, introduced in React 16.8, enable functional components to use state and lifecycle features:

import React, { useState } from 'react';

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

    return (
        

Count: {count}

); }

Explanation: The useState hook manages the count state directly in a functional component.

6. Composition of Components

React components can be nested to create complex UIs:

function Header() {
    return 

My App

; } function Footer() { return

© 2024 My Company

; } function App() { return (

Welcome to the app!

); }

This demonstrates how small, focused components can be combined to form a complete application.

Additional Resources