Level 1: Introduction to React
React (also known as React.js or ReactJS) is an open-source, component-based front-end JavaScript library maintained by Meta (formerly Facebook). Created to overcome the performance bottlenecks and state-synchronization problems of traditional DOM manipulation, React powers modern web user interfaces by isolating changes and selectively updating only the modified elements of a webpage.
1. What is React? (Library vs. Framework)
React is fundamentally a JavaScript library, not a full-fledged framework. Understanding this distinction is essential for every developer:
- Framework (e.g., Angular, Next.js): Imposes an all-inclusive, opinionated architecture. It dictates routing, HTTP clients, project structure, and state management rules. The framework calls your code.
- Library (React): Focuses strictly on one concern: building dynamic user interfaces (UIs). React gives you the building blocks—primarily components—and leaves architectural decisions such as routing, data fetching, and build pipelines up to the developer.
Key Architectural Traits of React
- Free and Open Source: Developed, maintained, and continually enhanced by Meta and an extensive global open-source community.
- Component-Based Architecture: Breaks complex user interfaces into independent, reusable, and self-contained units known as components (traditionally Class-based, modernly Function-based).
- Declarative Paradigm: You describe what the UI should look like for a given state, and React handles the low-level DOM mutations to match that state.
2. Understanding Single Page Applications (SPAs)
Traditional web applications rely on multi-page round-trips. Whenever a user clicks a navigation link, the browser issues a full HTTP request, shows a blank screen or a browser-level loading spinner in the tab, downloads a fresh HTML document, and parses the entire document object model from scratch.
React enables Single Page Applications (SPAs):
The User Experience Difference
- Traditional Multi-Page App (MPA):
Click /learnBrowser tab loader spins Entire screen flickers/blanks Full page reloads. - Single Page Application (SPA):
Click /learnNo browser reload spinner Instantaneous transition The user stays inside the same physicalindex.htmlpage while the UI swaps out components seamlessly.
3. Why Was React Created? The Problem with Traditional DOM Manipulation
Before React was introduced in 2013, web developers relied on vanilla JavaScript or libraries like jQuery to directly query and mutate the browser's Document Object Model (DOM).
While simple for static or small websites, this imperative model struggles at scale:
- Expensive DOM Operations: The browser DOM is inherently slow to manipulate. Whenever a DOM node is inserted, removed, or edited, the browser triggers costly reflows (re-calculating element geometry and positions) and repaints (re-rasterizing pixels to the screen).
- Cascading Updates: In complex apps like Facebook, changing a single data point (e.g., an unread notification count) often caused entire containers, parent wrappers, or unrelated sibling trees to re-render.
Real-World Production Problem: The Facebook Notification Badge
Consider the Facebook notification bell icon. If you have 4 notifications and receive a new one, the badge count must change from 4 to 5:
- The Flawed Approach (Naive DOM): To update that badge, large chunks of the surrounding navigation bar and news feed were re-rendered or repainted, causing UI lag and battery drain.
- The Optimized React Approach: React surgically isolates the badge element, diffs it against its previous state, and mutates only the single text node from
4to5, leaving the rest of the application completely untouched.
4. The Mental Model: The Punished Classroom Analogy
To grasp why direct DOM manipulation degrades performance and how React fixes it, consider this classroom scenario:
Real-Life Analogy: The Misbehaving Backbencher
Imagine a noisy classroom where a single student sitting on the back bench yells out during a quiet study session. A strict teacher walks in, demanding to know who caused the disruption.
- The Vanilla JavaScript Approach: Because nobody identifies the culprit, the teacher loses patience and punishes the entire class—forcing every innocent student to suffer along with the single noisy child. In web terms: one element (
<h1>) needed an update, but the browser ended up re-parsing, reflowing, and repainting the entire page.- The React Approach: React acts like an omniscient teacher equipped with a targeted surveillance system. It identifies the exact child who yelled, walks directly to their desk, issues the punishment solely to them, and leaves the rest of the class to continue working without interruption.
By avoiding unnecessary re-renders of unchanged DOM elements, React keeps applications highly responsive and performant even under heavy state updates.
5. Vanilla JS DOM Manipulation vs. React's Approach
To see the fundamental shift, compare how an <h1> element with the text "Virtual Code" is created and injected into a root container using Vanilla JavaScript versus React.
1. The Vanilla JavaScript Implementation (Imperative)
Here, we give the browser step-by-step instructions on how to build each piece of the DOM node:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vanilla JS DOM</title>
</head>
<body>
<div id="root"></div>
<script src="script.js"></script>
</body>
</html>
// script.js
// Step 1: Create the element
const h1 = document.createElement("h1");
// Step 2: Set its properties / inner content
h1.innerText = "Virtual Code";
// Step 3: Find the parent container in the DOM
const root = document.getElementById("root");
// Step 4: Mutate the DOM tree by appending the child
root.appendChild(h1);
2. The React CDN Implementation (Declarative Element Creation)
Before introducing complex build tools like Vite or Webpack, React can be introduced into an HTML document via Content Delivery Network (CDN) script tags.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React via CDN</title>
</head>
<body>
<div id="root"></div>
<!-- 1. React Core Library: Responsible for creating elements & component logic -->
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<!-- 2. ReactDOM Library: Responsible for mounting React elements into the Browser DOM -->
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<!-- Application Entrypoint -->
<script src="script.js"></script>
</body>
</html>
// script.js
// Step 1: Create a React element (tag, props/attributes, children)
const h1 = React.createElement(
"h1",
null, // No attributes/props passed
"Virtual Code" // Child text content
);
// Step 2: Establish the mounting boundary (Root) inside the real DOM
const rootContainer = document.getElementById("root");
const root = ReactDOM.createRoot(rootContainer);
// Step 3: Instruct React to render the element into that root
root.render(h1);
6. Hands-On: Setting Up React via CDN
Using CDNs provides an unabstracted view of what React is doing under the hood before toolchains (like Node.js, NPM, and bundlers) enter the picture.
Step-by-Step Setup:
- Create a project directory:
react-tutorial. - Inside the folder, create two files:
index.htmlandscript.js. - Open the directory in your code editor (e.g., VS Code).
- Add the root container
<div id="root"></div>toindex.html. - Import both the React and ReactDOM CDN scripts before your custom
script.js. - Serve the files using an HTTP server (e.g., the VS Code Live Server extension) to view live changes in the browser.
7. Deep Dive: React.createElement vs. ReactDOM.createRoot
Writing React without JSX reveals the exact function calls that form React's underlying architecture:
1. React.createElement(type, props, ...children)
This method produces a plain JavaScript object representing a virtual DOM node.
type: A string indicating the HTML tag name (e.g.,'h1','p','div') or a React component reference.props: An object containing attributes (such asid,className, inline styles, or event handlers) passed to the element. Passnullif no properties are required.children: The nested content or inner nodes. This can be plain text, another React element, or an array of elements.
Note: Executing
React.createElement()alone does not display anything on the screen. It merely creates an in-memory representation of the UI element.
2. ReactDOM.createRoot(domNode)
Introduced in modern React (version 18+), createRoot sets up the container where your React tree will live inside the browser's physical DOM.
- It takes a reference to an existing browser element (
document.getElementById("root")). - It returns a React root object configured with concurrent rendering capabilities.
3. root.render(reactElement)
Takes the virtual representation created by React.createElement and translates it into actual browser DOM nodes, appending them efficiently into the designated container.
8. The Separation of Concerns: React, ReactDOM, and React Native
A common point of confusion is why React requires two separate scripts (react.js and react-dom.js) instead of one unified file.
React follows a modular decoupled architecture:
The Role of Each Package
By decoupling the core UI logic from the rendering platform, Meta allows engineers to use the exact same mental models across both web and native mobile development.
9. Architectural Comparison: Imperative vs. Declarative Workflow
To synthesize what occurs in memory and in the browser, review the contrasting operational workflows:
Summary and Key Takeaways
- React is a UI Library: React is not a heavy, monolithic framework; it is an open-source JavaScript library strictly focused on building component-based user interfaces.
- Single Page Applications (SPAs): SPAs swap out components dynamically in response to user actions without triggering full browser reloads or URL spinners.
- Targeted Re-rendering: Vanilla DOM manipulation forces costly reflows across wide sections of a webpage. React minimizes browser overhead by updating only the specific DOM nodes whose data or state has changed.
- The Classroom Analogy: While vanilla JavaScript's direct DOM mutation often punishes the "entire class" (re-rendering entire parent trees), React isolates and punishes "only the noisy student" (the node that actually changed).
- Two-Part Architecture:
Reactcreates elements, tracks changes, and manages component structures.ReactDOMacts as the bridge that physically takes those elements and displays them inside a web browser's DOM.
- Cross-Platform Flexibility: Because React core is decoupled from the rendering layer, the same design principles can power web apps via
ReactDOMand native mobile apps viaReact Native. - CDN vs. Production Builds: While professional development relies on build tools and bundlers (covered in Level 2), setting up React via CDN reveals the essential foundation:
React.createElement()builds the component, andReactDOM.createRoot().render()brings it to life on the screen.