Course Lessons

JAVASCRIPT FOUNDATIONS + AI MINDSET

Back to Course

INTRO TO REACT

JAVASCRIPT... Lesson 21 of 41 8 min

Introduction to React

Build Interactive UIs with Components & State

By AI Learning Assistant  ·  React  ·  JSX  ·  Hooks

🤖 AI-POWERED LESSON

This article is paired with a live AI session. You will learn to build modern user interfaces with React  the library used by Facebook, Netflix, Airbnb, and millions of developers worldwide. Every code block includes detailed line-by-line comments.

React is a JavaScript library for building user interfaces. It was created by Facebook in 2013 and has become the most popular frontend framework in the world. But React isn't a framework  it's a library focused entirely on the view layer: how your UI looks and how it responds to user input.

The genius of React is its component model. You break your UI into small, reusable pieces (components), each managing its own state. These components update automatically when their state changes, and React efficiently figures out what to re-render. No more manual DOM manipulation with document.getElementById and innerHTML.

We will cover creating a React app with Create React App, JSX syntax (HTML inside JavaScript), useState hook for managing data, conditional rendering, and the Virtual DOM  the secret behind React's performance. By the end, you'll have a working enrollment form that remembers names and shows personalized messages.

What is JSX?

HTML-LIKE SYNTAX · JAVASCRIPT POWER

JSX (JavaScript XML) is a syntax extension that lets you write HTML-like code directly inside your JavaScript. It gets compiled to regular JavaScript by tools like Babel. JSX makes React code readable and intuitive — you can see the UI structure right alongside the logic that powers it.

In JSX, you embed JavaScript expressions inside curly braces { }. You can also use all HTML attributes, but with a few differences: className instead of class, onClick instead of onclick, and inline styles as objects: style={{ padding: "20px" }}.

📜 SETUP: Create Your First React App (Terminal Commands)

// ============================================
// STEP 1: CREATE A NEW REACT APP
// ============================================
// WHY: Create React App is the official tool to bootstrap React projects
// It sets up everything: Webpack, Babel, development server, hot reloading
// npx runs the command without permanently installing it globally
npx create-react-app webbo3-react

// STEP 2: NAVIGATE INTO THE PROJECT FOLDER
cd webbo3-react

// STEP 3: START THE DEVELOPMENT SERVER
// WHY: npm start launches a local server at http://localhost:3000
// It also enables hot reloading — any code change instantly updates the browser
npm start

// Your browser will automatically open to http://localhost:3000
// You should see the default React logo spinning

// STEP 4: EDIT src/App.js with the code from CODE BLOCK 2
// The changes will appear instantly in your browser
    

Build the Enrollment App

USE STATE · CONDITIONAL RENDERING · EVENT HANDLERS

📜 CODE BLOCK 2: Complete src/App.js (with line-by-line comments)

// ============================================
// REACT ENROLLMENT APP
// ============================================

// WHY: Import React and the useState hook
// useState lets components have their own data that triggers re-renders when changed
import React, { useState } from "react";

// WHY: App is the root component of our entire application
// Every React app has at least one component
function App() {
  
  // WHY: useState returns an array with two elements: current state and a setter function
  // Array destructuring extracts them into variables
  // [name] holds the current value, [setName] updates it and triggers re-render
  const [name, setName] = useState("");      // Initially empty string
  const [enrolled, setEnrolled] = useState(false);  // Initially not enrolled

  // WHY: Event handler called when user clicks "Enroll Now"
  // HOW: Checks if name is not just whitespace before enrolling
  const handleEnroll = () => {
    // .trim() removes leading/trailing whitespace
    // If the user typed something meaningful, set enrolled to true
    if (name.trim() !== "") {
      setEnrolled(true);
    }
  };

  // WHY: JSX — HTML-like syntax inside JavaScript
  // The component must return a single parent element (here, a div)
  // Inline styles in React are objects with camelCase properties
  return (
    <div style={{ padding: "40px", fontFamily: "Arial" }}>
      <h1>Welcome to Webbo3h1>
      <h2>JavaScript Mastery Course — Cohort 01h2>
      
      // CONDITIONAL RENDERING: Show different UI based on enrolled state
      {!enrolled ? (
        // NOT ENROLLED: Show form with input and button
        <div>
          <input
            placeholder="Enter your name"
            value={name}
            // onChange runs every time the user types
            // e.target.value contains what the user typed
            onChange={e => setName(e.target.value)}
          />
          <button onClick={handleEnroll}>Enroll Nowbutton>
        div>
      ) : (
        // ENROLLED: Show welcome message with user's name
        <p style={{ color: "green" }}>
          Welcome, {name}! You are enrolled in Cohort 01.
        p>
      )}
    div>
  );
}

// WHY: Export the component so it can be imported and rendered in index.js
export default App;

// ============================================
// HOW THE DATA FLOWS
// ============================================
// 1. User types in input → onChange fires → setName updates state
// 2. setName triggers a re-render of the component
// 3. The input's value prop gets the new name (controlled component)
// 4. User clicks Enroll → handleEnroll runs → setEnrolled(true)
// 5. setEnrolled triggers re-render → ternary shows welcome message instead of form
    

🎯 Live Demo: Try the React Enrollment Form (simulated)

Welcome to Webbo3

JavaScript Mastery Course — Cohort 01

⬆️ This is exactly what your React app will look like! Type your name and click Enroll.

LIVE AI LEARNING SESSION

Ask your AI assistant this question ↓

💬 YOU ASK THE AI:

"What is the virtual DOM in React and how is it different from the real DOM? Why does this make React faster?"

🤖 AI RESPONDS:

The Real DOM (Document Object Model) is the browser's representation of your HTML. It's a tree of objects that the browser uses to paint pixels on the screen. Manipulating the real DOM is slow because every change can cause the browser to recalculate styles, reflow layout, and repaint — expensive operations.

The Virtual DOM is a lightweight JavaScript object that React maintains in memory. It's a copy of the real DOM structure, but much cheaper to create and update because it's just a plain JavaScript object, not attached to the browser's rendering engine.

How React uses it:

1. When state changes (like setName or setEnrolled), React creates a new Virtual DOM tree reflecting the new state.
2. React compares (diffs) the new Virtual DOM against the previous Virtual DOM snapshot.
3. React identifies the minimal set of changes needed.
4. React applies ONLY those changes to the real DOM — batching updates efficiently.

Why this is faster: Instead of directly manipulating the real DOM (which is slow), React does all the expensive diffing in JavaScript (fast), then makes a single batch update to the real DOM. Without the Virtual DOM, updating 10 pieces of state could cause 10 separate real DOM updates, each triggering layout recalculations. With the Virtual DOM, React batches them into ONE real DOM update.

Analogy: The real DOM is like rearranging furniture in a house — every move takes time and effort. The Virtual DOM is like planning the move on paper first — you figure out exactly what needs to move where, then do all the moving at once. Much more efficient!

📝 MY NOTE — IN MY OWN WORDS

The Virtual DOM concept finally clicked. I used to think React was magic, but now I understand it's just smart diffing. The analogy of rearranging furniture vs planning on paper is perfect. I built the enrollment app and it worked immediately — I could see how state changes automatically update the UI without any DOM manipulation code. The conditional rendering with ternary operator is so much cleaner than if statements. I am excited to learn more React. Next, I want to add a list of enrolled students using an array state and map().

JSX Rules & Gotchas

COMMON MISTAKES · QUICK REFERENCE

// ============================================
// JSX RULES (CRITICAL FOR BEGINNERS)
// ============================================

// 1. RETURN A SINGLE PARENT ELEMENT
// ❌ WRONG: Returning two sibling elements
// return (
//   

Title

//

Paragraph

// ); // ✅ CORRECT: Wrap in a fragment or div // return ( // <> //

Title

//

Paragraph

// // ); // 2. USE className INSTEAD OF class // ❌
// ✅
// 3. EMBED JAVASCRIPT IN CURLY BRACES // ✅

Hello, {userName}!

// ✅ // 4. INLINE STYLES ARE OBJECTS WITH CAMELCASE // ✅ style={{ backgroundColor: "blue", fontSize: "16px" }} // 5. EVENT HANDLERS USE CAMELCASE // ✅ onClick, onSubmit, onChange (not onclick, onsubmit) // 6. SELF-CLOSING TAGS NEED FORWARD SLASH // ✅

Understanding useState

THE HEART OF REACT COMPONENTS

🎯 useState Hook Explanation

What it does: useState lets functional components have local state. It returns an array with two items: the current state value, and a function to update it. When the update function is called, React re-renders the component with the new state.

Common mistake: Directly mutating state. Always use the setter function: setName("new name") not name = "new name". React relies on the setter to know when to re-render.

🤖 HOW AI ACCELERATES REACT LEARNING

Ask AI: "I'm getting a 'React Hook useState is called conditionally' error. What does this mean and how do I fix it?" Get immediate help with React's rules of hooks.

Ask: "Explain the difference between props and state in React with examples." Learn the core architectural pattern of React.

Ask: "Convert this jQuery code that manipulates the DOM to React using state and JSX." See how React replaces imperative DOM code with declarative components.

AI-Assisted JavaScript Learning · Introduction to React · Build Component-Based UIs

Complete this lesson

Mark as complete to track your progress