1. Introduction to React
What is React and Component-Based Architecture
React is a declarative, efficient, and flexible JavaScript library for building user interfaces, originally created by Meta (Facebook). Unlike traditional frameworks like Angular which enforce strict MVC (Model-View-Controller) structures, React focuses solely on the View layer. It introduces a paradigm shift: Component-Based Architecture.
Instead of building monolithic HTML pages, you break the UI into isolated, reusable pieces called components. Think of components as custom HTML elements that encapsulate their own structure, styling, and behavior. This modularity enforces a separation of concerns at the component level rather than at the technology level (putting HTML, CSS, and JS together per component).
Core Concepts and Rules:
- Declarative UI: You describe what the UI should look like for a given state, and React figures out how to update the DOM to match it. You do not imperatively mutate the DOM (e.g., using
document.getElementById). - Unidirectional Data Flow: Data always flows down the component tree. A parent passes data to a child via props. A child cannot directly modify the parent's data.
- Pure Components: A React component should ideally be a pure function concerning its props; it should always return the same output for the same input without causing side effects.
// A simple functional component in React // Notice how it looks like a JavaScript function that returns HTML. function WelcomeProfile({ name, role }) { return ( <div className="profile-card"> <h1>Welcome, {name}!</h1> <p>Your role is: <strong>{role}</strong></p> <button onClick={() => alert('Profile clicked!')}>View Details</button>
SPA vs MPA: Understanding the Web Landscape
To understand React's dominance, you must grasp the difference between a Multi-Page Application (MPA) and a Single-Page Application (SPA).
Historically, the web ran on the MPA model. When a user clicked a link, the browser sent a request to the server, which computed the HTML and sent a completely new page back. This caused the browser to flash white, re-download all CSS and JavaScript, and lose any local memory state.
React powers SPAs. In an SPA, the browser downloads a single HTML file (usually just an empty <div id="root"></div>) and a large JavaScript bundle. From that point on, React takes over routing and rendering. When the user navigates, React intercepts the click, fetches raw data (like JSON) via an API if necessary, and dynamically updates the DOM. The page never reloads.
Trade-offs and Variations:
- Pros of SPA: Fluid, native-app-like user experience. State persists across navigations (like a playing music player). Less server overhead since it only sends JSON instead of rendering HTML.
- Cons of SPA: Slower initial load time (must download the JS bundle). Poor default SEO because web crawlers initially see a blank HTML file (solved by SSR frameworks like Next.js).
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; // Demonstrating SPA Navigation // Notice how we use <Link> instead of <a>. // <a> causes a full page reload, <Link> triggers React's internal router. function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> {/* React swaps out the component here based on the URL */} <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); } const Home = () => <h2>Home Page - No refresh needed!</h2>; const About = () => <h2>About Page - Instant navigation!</h2>;
The Virtual DOM and Reconciliation
Directly mutating the browser's Document Object Model (DOM) is computationally expensive. Every time you change a node, the browser may have to recalculate CSS styles, layout dimensions, and repaint the screen.
React solves this performance bottleneck using the Virtual DOM. The Virtual DOM is a lightweight, in-memory JavaScript representation of the actual DOM. When your component's state changes, React does not touch the real DOM immediately. Instead, it generates a completely new Virtual DOM tree.
React then performs a process called Reconciliation. It compares (diffs) the new Virtual DOM tree against a snapshot of the previous Virtual DOM tree. Using a highly optimized heuristic algorithm (the Diffing Algorithm), React calculates the absolute minimum number of changes required to synchronize the real DOM with the new state. Finally, it batches these changes and applies them to the real DOM in one swift operation.
Rules of the Diffing Algorithm:
- Different Element Types: If a
<div>changes to a<span>, React immediately tears down the old tree and builds a new one from scratch. State is destroyed. - Same Element Types: If the element remains the same, React preserves the DOM node and only updates the changed attributes (like
classNameorstyle). - Component Identity: If a component unmounts and remounts, its internal state is completely wiped.
import { useState } from 'react'; function VirtualDomDemo() { const [isToggled, setIsToggled] = useState(false); return ( <div> <button onClick={() => setIsToggled(!isToggled)}> Trigger Reconciliation </button> {/* If toggled, React just updates the text node of the h3. It does NOT recreate the h3 element. */} <h3>Status: {isToggled ? 'Active' : 'Inactive'}</h3> {/* If toggled, React destroys the <section> and builds an <article>. This is expensive and destroys any internal state within those tags. */} {isToggled ? ( <section>Section Container</section> ) : ( <article>Article Container</article> )}
Setting Up React with Vite
Vite is the industry-standard build tool for React projects. Unlike older bundlers like Webpack, Vite leverages native ES Modules in the browser to start your development server nearly instantaneously. To get started, open your terminal and run the following commands:
npm create vite@latest my-app -- --template react-ts cd my-app npm install npm run dev
When running the command, ensure you select TypeScript for type safety. Once installed, your directory structure will look like this:
my-app/ ├── src/ │ ├── App.tsx # Your main component │ ├── main.tsx # Entry point connecting React to the HTML │ └── index.css # Global styles ├── index.html # The root HTML file └── package.json # Dependencies and scripts
In main.tsx, React uses createRoot to mount your App component into the div#root element inside index.html. This is the bridge where your JS-based UI takes over the document.
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; ReactDOM.createRoot(document.getElementById('root')!).render(<App />);
Line 1-2 import the React library and the ReactDOM rendering engine. Line 3 imports your root component. The createRoot function initializes the reconciliation process on the specified DOM node.
Knowledge Check
Ready to test your understanding of 1. Introduction to React?