React Basics: Components, JSX, Props, and State

1. Components in React: Functional vs. Class

What are Components?
Components are the building blocks of React applications. They enable you to break down the UI into reusable, independent pieces.

Types of Components:

  1. Functional Components

    • Simple JavaScript functions that return JSX.
    • Introduced with React Hooks, they can now manage state and lifecycle.
    • Preferred for modern development.

    Example:

import React from 'react';

function Greeting() {
  return <h1>Hello, World!</h1>;
}

export default Greeting;

2. Class Components

  • Require the class keyword and extend React.Component.
  • Can manage state and lifecycle without hooks (older syntax).

Example:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}

export default Greeting;

Key Differences:

FeatureFunctional ComponentsClass Components
SyntaxFunction-basedClass-based
State ManagementuseState and hooksthis.state
PerformanceSlightly fasterRequires more overhead
UsageModern React developmentLegacy codebases

JSX Syntax and Rules

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It simplifies creating and rendering React components.

Example JSX Code:

const element = <h1>Hello, JSX!</h1>;

Rules of JSX:

  1. Single Root Element: Wrap all JSX in a single root element.

return (
  <div>
    <h1>Hello</h1>
    <p>Welcome to React!</p>
  </div>
);

JavaScript Expressions: Embed JavaScript using curly braces {}.

const name = 'React Developer';
return <h1>Welcome, {name}!</h1>;

Self-Closing Tags: Close tags for elements without children.

 
<img src="logo.png" alt="React Logo" />

CSS Class Names: Use className instead of class.

<div className="container">Hello</div>

Conditionals in JSX: Use ternary operators for conditional rendering.

const isLoggedIn = true;
return <h1>{isLoggedIn ? 'Welcome Back!' : 'Please Log In'}</h1>;

Props and State

Props (Properties):
Props are used to pass data from one component to another, making components reusable and dynamic. Props are read-only and cannot be modified by the receiving component.

Example Using Props:

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

// Using the component
<Welcome name="John" />

State:
State is a built-in object that holds data or information about a component. Unlike props, state is mutable and managed within the component itself.

Using State in Functional Components (with Hooks):

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default Counter;

Using State in Class Components:

import React, { Component } from 'react';

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

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increase
        </button>
      </div>
    );
  }
}

export default Counter;

Key Differences Between Props and State

FeaturePropsState
Data FlowPassed from parent to childManaged within component
MutabilityImmutable (read-only)Mutable
UsageFor configurationFor dynamic behavior

Best Practices

  • Use Functional Components: Prefer functional components with hooks over class components for new projects.
  • Keep JSX Clean: Split complex JSX into smaller components.
  • Leverage Props for Reusability: Pass only necessary data to child components.
  • Minimize State: Keep state minimal and colocated to where it’s needed.
  • Separate Concerns: Use props for parent-to-child communication and state for local management.