React Tutorial
Build fast, interactive user interfaces with components, JSX, and the Virtual DOM
Table of Contents
1. What is React?
React (also known as React.js or ReactJS) is an open-source JavaScript library for building user interfaces (UIs), specifically for single-page applications.
- Created by: Facebook (now Meta) in 2013.
- Core purpose: To build fast, interactive, and reusable UI components.
- Not a framework: Unlike Angular or Vue, React is just a library focused only on the "view" layer (the part the user sees). For full features (routing, state management, API calls), you add extra libraries.
- The key idea: Break your UI into small, independent, reusable pieces called components.
2. Key Features of React
| Feature | What it means |
|---|---|
| Component-Based Architecture | Build encapsulated components that manage their own state, then compose them to make complex UIs. |
| Declarative Syntax | You describe what the UI should look like for a given state, and React handles how to update the DOM efficiently. |
| JSX (JavaScript XML) | A syntax extension that lets you write HTML-like code inside JavaScript. Makes component code easier to read/write. |
| Virtual DOM | A lightweight copy of the real DOM. React uses it for high-performance updates (explained in detail below). |
| One-Way Data Binding | Data flows from parent to child via props. This makes debugging easier because you know exactly where data changes. |
| Hooks | Functions like useState, useEffect that let you "hook into" React state and lifecycle features from functional components. |
| React Native | Use React knowledge to build native mobile apps for iOS and Android. |
3. Advantages of React
| Advantage | Explanation |
|---|---|
| Fast & Efficient | The Virtual DOM + diffing algorithm makes UI updates very fast, even for complex, data-heavy apps. |
| Reusable Components | Write once, use everywhere. Reduces development time and keeps code DRY (Don't Repeat Yourself). |
| Strong Community & Ecosystem | Backed by Facebook and millions of developers. Thousands of third-party libraries, tools, and tutorials available. |
| SEO-Friendly (with Next.js) | Standard React can hurt SEO (since it's client-side). But with frameworks like Next.js (server-side rendering), React becomes very SEO-friendly. |
| Easy to Learn & Use | If you know HTML, CSS, and JavaScript, you can learn React basics in a few days. Much gentler curve than Angular. |
| Great Developer Experience | Hot reloading, excellent browser devtools, helpful error messages. |
| Backed by a Big Company | Continuous updates, long-term support, and trust from enterprises. |
Real-world users: Facebook, Instagram, Netflix, Airbnb, Uber, WhatsApp Web, Dropbox.
4. Single Page Application (SPA) Concept
To understand React, you must first understand the problem it solves: traditional multi-page applications vs. SPAs.
Traditional (Multi-Page) Website
Browser requests a page → Server sends full HTML → Browser reloads entire page.
Problem: Slow, jarring full-page reloads, even for small changes.
Single Page Application (SPA)
Concept: The browser loads a single HTML page once. All subsequent interactions (clicks, form submits, navigation) happen without refreshing the page.
How it works: JavaScript (like React) fetches only the data needed (e.g., JSON from an API) and dynamically rewrites the current page content.
SPA Analogy: A traditional website is like a book – you turn every page (full reload). An SPA is like a digital map – you pan and zoom (update parts) without ever getting a new piece of paper.
SPA Characteristics
- No page reloads during usage.
- Faster and smoother user experience (feels like a desktop app).
- Routes are handled client-side (e.g., React Router).
- Initial load may be slower, but subsequent navigation is instant.
Examples of SPAs: Gmail, Google Maps, Facebook, Twitter, GitHub.
React + SPA
React is perfect for building SPAs because:
- Its component model matches the "chunks of UI" you update dynamically.
- The Virtual DOM makes those updates fast.
- Libraries like
react-router-domhandle client-side navigation.
5. Virtual DOM – The Heart of React's Performance
This is the most important concept for interviews and understanding React's magic.
The Problem with the Real DOM
- The Real DOM (Document Object Model) is the browser's representation of your HTML.
- Manipulating the Real DOM directly is slow – every change can cause the browser to recalculate layout, repaint, and reflow.
- Frequent updates (e.g., a chat app with many messages per second) can make the UI feel laggy.
The Virtual DOM Solution
React creates a Virtual DOM – a lightweight JavaScript object representation of the Real DOM.
How it works (in 4 steps):
- Render Phase (in memory): When a component's state changes, React creates a new Virtual DOM tree representing what the UI should look like.
- Diffing: React compares the new Virtual DOM tree with the previous Virtual DOM tree (stored in memory). This comparison is called "diffing" and is very fast because it's just JavaScript objects.
- Calculate Minimal Changes: React identifies the exact differences (e.g., "this text changed", "this button was added").
- Re-render Phase (Real DOM update): React updates only those specific elements in the Real DOM. This is called reconciliation.
Visual Example
Imagine a to-do list with 100 items. You mark one item as "completed".
- Without Virtual DOM (bad): The app might clear the entire list and redraw all 100 items (slow).
- With Virtual DOM (React): React's diffing sees that only one
<li>changed. It updates just that one line in the Real DOM (fast).
Virtual DOM vs. Real DOM – Comparison Table
| Aspect | Real DOM | Virtual DOM |
|---|---|---|
| Nature | Browser API object | Plain JavaScript object |
| Update Speed | Slow (reflows, repaints) | Fast (just memory operations) |
| Updates | Directly manipulates UI | Updates in memory, then syncs minimal changes |
| Memory | Higher overhead | Lightweight |
Important: The Virtual DOM is not "faster" than the Real DOM. It's a strategy to minimize expensive Real DOM operations by batching and optimizing updates.
6. Putting It All Together: A Simple React Example
What happens when you click the button?
setCountupdates the state.- React creates a new Virtual DOM with
count = 1. - React diffs old VDOM (
count=0) vs. new VDOM (count=1). It finds the<h1>text changed. - React updates only that one text node in the Real DOM.
- No page reload. The UI updates instantly (SPA behavior).
7. Summary Cheat Sheet
| Concept | One-Line Summary |
|---|---|
| React | A library for building UI components. |
| Component | A reusable, self-contained piece of UI. |
| JSX | HTML-like syntax inside JavaScript. |
| Virtual DOM | A lightweight copy of the real DOM used for efficient updates. |
| Diffing | Comparing old and new Virtual DOM to find changes. |
| Reconciliation | The process of updating only changed parts of the real DOM. |
| SPA | A web app that loads a single HTML page and updates dynamically without reloads. |
| State | Data that changes over time within a component. |
| Props | Data passed from a parent to a child component. |
React MCQ Practice
10 Basic MCQs 10 Advanced MCQs10 Basic React MCQs
What is React?
Who originally created React?
What is JSX?
SPA stands for:
The Virtual DOM is:
Data passed from parent to child component is called:
useState returns:
const [count, setCount] = useState(0) is the common destructuring pattern.When component state changes, React:
React is best described as a:
To add React to an existing project, you typically run:
react and react-dom for rendering to the browser.10 Advanced React MCQs
What is reconciliation in React?
useEffect runs after:
The key prop in lists helps React:
A controlled component means:
React.Fragment is used to:
<div>.One-way data binding in React helps because:
createRoot from react-dom/client is used to:
createRoot(document.getElementById('root')).render(<App />) is the modern entry pattern."Lifting state up" means:
Conditional rendering in JSX commonly uses:
{isLoggedIn ? <Dashboard /> : <Login />} or {error && <p>{error}</p>}.React Strict Mode helps developers by:
15 Interview Questions & Answers
Easy Medium HardReact.createElement calls.useState) that triggers re-renders when updated.useState, useEffect, and useContext that let functional components use state, side effects, and other React features without class components.useState vs useEffect?mediumuseState stores data that changes over time inside a component. useEffect runs side effects after render—API calls, subscriptions, timers, or syncing with external systems.value + onChange). Uncontrolled components keep values in the DOM and are accessed via refs—useful for simple forms or file inputs.React.memo, useMemo, and useCallback to avoid unnecessary re-renders; virtualize long lists; code-split with lazy loading; keep state local; avoid inline object/function props when they cause child re-renders; and profile with React DevTools.