Topic 1 of 56 · Full Stack Advanced

Introduction to React

Lesson TL;DRTopic 1: Introduction to React 📖 8 min read · 🎯 beginner · 🧭 Prerequisites: introductionandfoundation, introductiontophpmyadmin Why this matters Up until now, you've been building web pages by writ...
8 min read·beginner·react · javascript · components · jsx

Topic 1: Introduction to React

📖 8 min read · 🎯 beginner · 🧭 Prerequisites: introduction-and-foundation, introduction-to-phpmyadmin

Why this matters

Up until now, you've been building web pages by writing HTML and JavaScript from scratch — and you've probably noticed it gets messy, fast. Change one thing, and something else breaks. The same button code copied in five places. It doesn't scale.

React is a JavaScript library built by Facebook that changes how you think about building UIs. Instead of writing a page, you build small, reusable pieces called components — like LEGO bricks — and snap them together. By the end of this lesson, you'll understand the seven ideas every React app is built on: components, JSX, props, state, event handling, conditional rendering, and list rendering.

What You'll Learn

  • Understand what React is and why its component-based architecture matters
  • Bootstrap a React project with Create React App and run the dev server
  • Write JSX and create functional components that accept props
  • Manage local component state with the useState hook
  • Handle click events, render conditionally, and display dynamic lists with keys

The Analogy

Think of a React application as a skyline made of prefabricated building modules. Each module (component) is designed once, tested in isolation, and then snapped into place wherever the city plan calls for it — a welcome sign here, a floor counter there, an entrance gate that knows whether you have a key. The city's blueprints (the virtual DOM) track only which modules changed since the last inspection, so the construction crew only re-pours the concrete that actually shifted rather than rebuilding the entire skyline from scratch. Data flows downward through the scaffolding from the top of the building to each floor below (unidirectional data flow), so there is never any confusion about who gave the orders.

Chapter 1: What is React?

React is a JavaScript library developed by Facebook for building user interfaces, particularly for single-page applications (SPAs). It allows developers to create reusable UI components, manage the state of an application efficiently, and ensure a seamless user experience — all without full page reloads.

Key Features of React

  1. Component-Based Architecture — Build encapsulated components that manage their own state, then compose them into complex UIs.
  2. Virtual DOM — React maintains a lightweight in-memory representation of the real DOM and efficiently updates and re-renders only the components that actually changed.
  3. Unidirectional Data Flow — Data moves in one direction (parent → child), making it far easier to debug and reason about application state.
  4. JSX Syntax — A syntax extension that combines JavaScript logic with HTML-like markup, making component authoring more intuitive.
graph TD
    A[App Component] --> B[Greeting]
    A --> C[Counter]
    A --> D[ClickButton]
    A --> E[ConditionalGreeting]
    A --> F[NumberList]
    style A fill:#4f46e5,color:#fff

Chapter 2: Setting Up a React Environment

the trainer projected the terminal onto the class wall. The quickest path to a working React project is Create React App, a tool that scaffolds a new project with a production-grade build pipeline (Webpack, Babel, ESLint) already configured — zero manual setup required.

Installing Create React App

npx create-react-app my-react-app

This command creates a new directory called my-react-app containing all necessary files and dependencies, including react, react-dom, and react-scripts.

Running the React Application

cd my-react-app
npm start

The development server starts and the default React application is now running at http://localhost:3000. Hot reloading is enabled — save a file and the browser updates instantly.

Project structure at a glance

my-react-app/
├── public/
│   └── index.html          ← the single HTML shell
├── src/
│   ├── App.js              ← root component
│   ├── App.css
│   └── index.js            ← ReactDOM.render entry point
└── package.json

Chapter 3: Understanding React Components

React applications are assembled from components — the building blocks of any React UI. Each component represents a discrete piece of the interface and is responsible for rendering its own HTML.

Creating a Simple Component

src/components/Greeting.js:

import React from 'react';

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

export default Greeting;

Using the Component

Once defined, a component is used like a custom HTML tag anywhere in the tree.

src/App.js:

import React from 'react';
import './App.css';
import Greeting from './components/Greeting';

function App() {
    return (
        <div className="App">
            <Greeting />
        </div>
    );
}

export default App;

The <Greeting /> tag tells React to call the Greeting function and insert its returned JSX into the page.

Chapter 4: JSX Syntax

JSX is a syntax extension for JavaScript that looks similar to HTML. It compiles down to React.createElement() calls — JSX is just syntactic sugar, but it dramatically improves readability.

Basic JSX element

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

Embedding JavaScript expressions in JSX

Any valid JavaScript expression can be embedded inside curly braces {}:

const name = "Alice";
const element = <h1>Hello, {name}!</h1>;

Rules to remember

  • JSX must return a single root element (wrap siblings in a <div> or <> fragment).
  • HTML attributes use camelCase: className instead of class, onClick instead of onclick.
  • Self-closing tags must end with /> (e.g., <img />).

Chapter 5: Props and State

Props and state are the two primary mechanisms for managing data in React — think of them as the city's supply chain: props are deliveries from outside (read-only), while state is the building's own internal inventory (mutable).

Props

Props (short for properties) are read-only attributes used to pass data from a parent component to a child component. The child never modifies its props.

src/components/Greeting.js — updated to accept a name prop:

import React from 'react';

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

export default Greeting;

src/App.js — passing the prop:

import React from 'react';
import './App.css';
import Greeting from './components/Greeting';

function App() {
    return (
        <div className="App">
            <Greeting name="Vizag" />
        </div>
    );
}

export default App;

State

State is a built-in mechanism that allows a component to create and manage its own data. When state changes, React re-renders the component automatically. Functional components use the useState hook.

src/components/Counter.js:

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>
    );
}

export default Counter;

src/App.js — adding Counter:

import React from 'react';
import './App.css';
import Greeting from './components/Greeting';
import Counter from './components/Counter';

function App() {
    return (
        <div className="App">
            <Greeting name="Vizag" />
            <Counter />
        </div>
    );
}

export default App;

useState(0) returns a tuple: the current value (count) and a setter function (setCount). Calling setCount with a new value schedules a re-render.

Chapter 6: Handling Events

Event handling in React is similar to DOM events, but with two differences: event names are camelCase (onClick not onclick), and you pass a function reference rather than a string.

src/components/ClickButton.js:

import React from 'react';

function ClickButton() {
    function handleClick() {
        alert('Button was clicked!');
    }

    return (
        <button onClick={handleClick}>
            Click me
        </button>
    );
}

export default ClickButton;

The handler function is defined inside the component (giving it access to state and props via closure) and referenced — not called — in the JSX: onClick={handleClick}, not onClick={handleClick()}.

Chapter 7: Conditional Rendering

React components can choose what to render based on JavaScript conditions — if statements, ternaries, and && short-circuits all work inside JSX.

src/components/ConditionalGreeting.js:

import React from 'react';

function ConditionalGreeting(props) {
    const isLoggedIn = props.isLoggedIn;

    if (isLoggedIn) {
        return <h1>Welcome back!</h1>;
    } else {
        return <h1>Please sign up.</h1>;
    }
}

export default ConditionalGreeting;

src/App.js — passing the boolean prop:

import React from 'react';
import './App.css';
import Greeting from './components/Greeting';
import Counter from './components/Counter';
import ClickButton from './components/ClickButton';
import ConditionalGreeting from './components/ConditionalGreeting';

function App() {
    return (
        <div className="App">
            <Greeting name="Vizag" />
            <Counter />
            <ClickButton />
            <ConditionalGreeting isLoggedIn={true} />
        </div>
    );
}

export default App;

Change isLoggedIn={false} and the component renders the sign-up message instead — no DOM manipulation needed.

Chapter 8: Lists and Keys

When rendering collections of data, React needs a key prop on each list item so the virtual DOM can track which items changed, were added, or were removed between renders. Keys must be unique among siblings.

src/components/NumberList.js:

import React from 'react';

function NumberList(props) {
    const numbers = props.numbers;
    const listItems = numbers.map((number) =>
        <li key={number.toString()}>
            {number}
        </li>
    );

    return (
        <ul>{listItems}</ul>
    );
}

export default NumberList;

src/App.js — final version with all components assembled:

import React from 'react';
import './App.css';
import Greeting from './components/Greeting';
import Counter from './components/Counter';
import ClickButton from './components/ClickButton';
import ConditionalGreeting from './components/ConditionalGreeting';
import NumberList from './components/NumberList';

function App() {
    const numbers = [1, 2, 3, 4, 5];

    return (
        <div className="App">
            <Greeting name="Vizag" />
            <Counter />
            <ClickButton />
            <ConditionalGreeting isLoggedIn={true} />
            <NumberList numbers={numbers} />
        </div>
    );
}

export default App;

The key prop is used internally by React and is not accessible as props.key inside the child component. If you need the value for other purposes, pass it as a separate prop.

🧪 Try It Yourself

Build a TodoList component that displays a dynamic list and lets the user add items.

Task: Create src/components/TodoList.js. It should render an input field and an "Add" button. When the button is clicked, the input value is appended to a list of to-do items displayed as <li> elements. Each <li> must have a unique key.

Success criterion: Type "Buy coffee" into the input, click Add, and see it appear in the list. Add three more items — all should appear without duplicates or React key warnings in the console.

Starter snippet:

import React, { useState } from 'react';

function TodoList() {
    const [items, setItems] = useState([]);
    const [inputValue, setInputValue] = useState('');

    function handleAdd() {
        if (inputValue.trim() === '') return;
        setItems([...items, { id: Date.now(), text: inputValue }]);
        setInputValue('');
    }

    return (
        <div>
            <input
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder="New to-do..."
            />
            <button onClick={handleAdd}>Add</button>
            <ul>
                {items.map((item) => (
                    <li key={item.id}>{item.text}</li>
                ))}
            </ul>
        </div>
    );
}

export default TodoList;

🔍 Checkpoint Quiz

Q1. What problem does the Virtual DOM solve in React, and why is it faster than directly manipulating the real DOM for every update?

Q2. Given this snippet, what does the browser display after the button is clicked three times?

import React, { useState } from 'react';

function Counter() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>+</button>
        </div>
    );
}

A) Count: 0
B) Count: 1
C) Count: 3
D) The component crashes because state cannot be modified

Q3. The following NumberList component is missing something critical that will generate a React warning. What is it and why does React require it?

function NumberList({ numbers }) {
    return (
        <ul>
            {numbers.map((n) => <li>{n}</li>)}
        </ul>
    );
}

A) The import React from 'react' statement
B) A key prop on each <li> element
C) The numbers array must be stored in state
D) <ul> must be wrapped in a <div>

Q4. You are building a dashboard that shows a "Welcome, Admin" banner only when user.role === 'admin'. Which React pattern would you use, and how would you write it inline inside JSX?

A1. The Virtual DOM is an in-memory representation of the real DOM. React diffs the new virtual DOM against the previous snapshot and applies only the minimum set of real DOM mutations needed. Touching the real DOM triggers expensive reflow/repaint operations; batching changes through the virtual DOM dramatically reduces those operations.

A2. C) Count: 3 — each click calls setCount(count + 1), incrementing state by 1 per click, so three clicks bring the count to 3 and the paragraph reads "Count: 3".

A3. B) A key prop on each <li>. React uses key to identify which list items changed, were added, or removed during reconciliation. Without keys, React cannot efficiently diff the list and may produce incorrect updates or poor performance.

A4. Use a short-circuit && expression or a ternary inside JSX:

{user.role === 'admin' && <p>Welcome, Admin</p>}

Or with a fallback using a ternary:

{user.role === 'admin' ? <p>Welcome, Admin</p> : null}

The && short-circuit renders the element only when the left-hand side is truthy; if it is falsy, React renders nothing.

🪞 Recap

  • React is a Facebook-developed JavaScript library for building component-based user interfaces with a Virtual DOM, unidirectional data flow, and JSX syntax.
  • npx create-react-app <name> bootstraps a full project; npm start launches the dev server at http://localhost:3000.
  • Components are JavaScript functions that return JSX; they are composed by using them as custom HTML tags inside other components.
  • Props are read-only data passed from parent to child; state is mutable local data managed with the useState hook.
  • Lists require a unique key prop on each rendered element so React can efficiently reconcile DOM changes.

📚 Further Reading

Like this topic? It’s one of 56 in Full Stack Advanced.

Block your seat for ₹2,500 and join the next cohort.