React Fundamentals: What is React and Why Use It?

Welcome to the World of Component-Based UI Development

Overview

Welcome to your first React lesson! Today, we'll explore what React is, why it's become the most popular JavaScript library for building user interfaces, and how it can revolutionize the way you think about web development. By the end of this session, you'll understand React's core concepts and be excited to start building with it.

What is React?

React is like a LEGO set for building websites. Just as LEGO gives you individual blocks that you can combine to create complex structures, React gives you components that you can combine to create sophisticated user interfaces.

graph TD A[React] --> B[JavaScript Library] A --> C[Created by Facebook] A --> D[Open Source] B --> E[For Building UIs] B --> F[Component-Based] B --> G[Declarative] C --> H[Used in Facebook, Instagram] C --> I[Maintained by Meta] D --> J[Large Community] D --> K[Extensive Ecosystem]

The Traditional Way vs. The React Way

Let's compare traditional web development to React development using a restaurant menu analogy:

Traditional Approach (DOM Manipulation)

Imagine you're a chef who needs to completely remake the entire menu board every time a single dish changes price. That's how traditional DOM manipulation works:


// Traditional JavaScript - Imperative Approach
const menuBoard = document.getElementById('menu');
const dishes = [
    { name: 'Pizza', price: 12 },
    { name: 'Pasta', price: 10 },
    { name: 'Salad', price: 8 }
];

function updateMenu() {
    menuBoard.innerHTML = ''; // Clear the entire board
    dishes.forEach(dish => {
        const item = document.createElement('div');
        item.innerHTML = `${dish.name}: $${dish.price}`;
        menuBoard.appendChild(item);
    });
}

// If one price changes, we redraw everything
dishes[0].price = 13;
updateMenu(); // Entire menu is redrawn
            

React Approach (Declarative)

With React, you're like a chef who just updates the specific price tag that changed. React figures out what needs to change and updates only that part:


// React - Declarative Approach
function Menu() {
    const [dishes, setDishes] = useState([
        { name: 'Pizza', price: 12 },
        { name: 'Pasta', price: 10 },
        { name: 'Salad', price: 8 }
    ]);

    return (
        <div>
            {dishes.map(dish => (
                <div key={dish.name}>
                    {dish.name}: ${dish.price}
                </div>
            ))}
        </div>
    );
}

// React automatically updates only what changed
setDishes(dishes.map(dish => 
    dish.name === 'Pizza' ? {...dish, price: 13} : dish
));
            

Why Use React?

1. Component-Based Architecture

Think of components like LEGO blocks or ingredients in a recipe. Each component is self-contained and reusable:

graph TD A[Web Page] --> B[Header Component] A --> C[Main Content] A --> D[Footer Component] C --> E[Article List] E --> F[Article Component] E --> G[Article Component] E --> H[Article Component] F --> I[Title] F --> J[Content] F --> K[Author Info]

// Reusable Button Component
function Button({ text, onClick, type = 'primary' }) {
    return (
        <button 
            className={`btn btn-${type}`}
            onClick={onClick}
        >
            {text}
        </button>
    );
}

// Use it anywhere
<Button text="Save" onClick={handleSave} />
<Button text="Cancel" onClick={handleCancel} type="secondary" />
<Button text="Delete" onClick={handleDelete} type="danger" />
            

2. Virtual DOM for Performance

The Virtual DOM is like having a blueprint before building. React creates a lightweight copy of the actual DOM, makes changes there first, then efficiently updates only what's necessary:

sequenceDiagram participant User participant React participant VirtualDOM participant RealDOM User->>React: Clicks button React->>VirtualDOM: Updates virtual tree VirtualDOM->>VirtualDOM: Calculates differences VirtualDOM->>RealDOM: Updates only changed elements RealDOM->>User: Shows updated UI

3. Unidirectional Data Flow

Data flows in one direction, like water flowing downstream. This makes it easier to understand and debug your application:

graph TD A[Parent Component] -->|Props| B[Child Component 1] A -->|Props| C[Child Component 2] B -->|Events| A C -->|Events| A A -->|State Update| A

Real-World Applications Using React

React's Core Concepts

1. Components

Components are like custom HTML elements you create. They can be functions or classes:


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

// Class Component (Legacy, but still used)
class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}

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

2. JSX (JavaScript XML)

JSX lets you write HTML-like code in JavaScript. It's like writing your recipe instructions directly in the language of cooking:


// JSX looks like HTML but it's JavaScript
const element = (
    <div className="greeting">
        <h1>Hello, world!</h1>
        <p>Welcome to React</p>
    </div>
);

// JSX is compiled to regular JavaScript
const element = React.createElement(
    'div',
    { className: 'greeting' },
    React.createElement('h1', null, 'Hello, world!'),
    React.createElement('p', null, 'Welcome to React')
);
            

3. Props (Properties)

Props are like ingredients you pass to a recipe. They're read-only and flow from parent to child:


// Parent component passing props
function RecipeBook() {
    return (
        <div>
            <Recipe 
                name="Chocolate Cake" 
                difficulty="Medium"
                prepTime={30}
            />
            <Recipe 
                name="Pancakes" 
                difficulty="Easy"
                prepTime={15}
            />
        </div>
    );
}

// Child component receiving props
function Recipe({ name, difficulty, prepTime }) {
    return (
        <div className="recipe">
            <h2>{name}</h2>
            <p>Difficulty: {difficulty}</p>
            <p>Prep Time: {prepTime} minutes</p>
        </div>
    );
}
            

4. State

State is like the current status of your kitchen appliances. It can change over time:


function Counter() {
    // State: the current count value
    const [count, setCount] = useState(0);

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

When to Use React?

React is perfect for:

React Ecosystem

graph TD A[React Core] --> B[React Router] A --> C[Redux/Context] A --> D[React Native] A --> E[Next.js] B --> F[Navigation] C --> G[State Management] D --> H[Mobile Apps] E --> I[Server-Side Rendering]

Getting Started with React

The easiest way to start a React project:


# Using Create React App
npx create-react-app my-first-react-app
cd my-first-react-app
npm start

# Using Vite (faster, modern alternative)
npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev
            

Your First React Component


// App.js
function App() {
    const [message, setMessage] = useState('Welcome to React!');
    
    const handleClick = () => {
        setMessage('You clicked the button!');
    };

    return (
        <div className="App">
            <h1>{message}</h1>
            <button onClick={handleClick}>
                Click Me
            </button>
        </div>
    );
}

export default App;
            

Practice Exercises

Exercise 1: Component Creation

Create a simple component that displays a user card with name, email, and avatar:


// Create a UserCard component
function UserCard({ name, email, avatar }) {
    // Your code here
}

// Usage:
<UserCard 
    name="John Doe" 
    email="john@example.com" 
    avatar="https://example.com/avatar.jpg" 
/>
            

Exercise 2: Interactive Component

Build a toggle button that switches between "ON" and "OFF":


function ToggleButton() {
    // Implement state to track ON/OFF
    // Change button text and style based on state
}
            

Exercise 3: List Rendering

Create a component that renders a list of tasks with checkboxes:


function TaskList() {
    const tasks = [
        { id: 1, text: 'Learn React', completed: false },
        { id: 2, text: 'Build a project', completed: false },
        { id: 3, text: 'Deploy to production', completed: false }
    ];
    
    // Render the task list with checkboxes
}
            

Key Takeaways

What's Next?

In our next lesson, we'll dive deeper into JSX syntax and learn how to create more complex components. We'll explore how to handle user input, work with forms, and manage component state effectively.

Homework