React Tutorial

Build fast, interactive user interfaces with components, JSX, and the Virtual DOM

Components Virtual DOM SPA Hooks

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.
JSX// A simple React component function Welcome() { return <h1>Hello, Developer!</h1>; }

2. Key Features of React

FeatureWhat it means
Component-Based ArchitectureBuild encapsulated components that manage their own state, then compose them to make complex UIs.
Declarative SyntaxYou 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 DOMA lightweight copy of the real DOM. React uses it for high-performance updates (explained in detail below).
One-Way Data BindingData flows from parent to child via props. This makes debugging easier because you know exactly where data changes.
HooksFunctions like useState, useEffect that let you "hook into" React state and lifecycle features from functional components.
React NativeUse React knowledge to build native mobile apps for iOS and Android.

3. Advantages of React

AdvantageExplanation
Fast & EfficientThe Virtual DOM + diffing algorithm makes UI updates very fast, even for complex, data-heavy apps.
Reusable ComponentsWrite once, use everywhere. Reduces development time and keeps code DRY (Don't Repeat Yourself).
Strong Community & EcosystemBacked 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 & UseIf you know HTML, CSS, and JavaScript, you can learn React basics in a few days. Much gentler curve than Angular.
Great Developer ExperienceHot reloading, excellent browser devtools, helpful error messages.
Backed by a Big CompanyContinuous 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-dom handle 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):

  1. Render Phase (in memory): When a component's state changes, React creates a new Virtual DOM tree representing what the UI should look like.
  2. 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.
  3. Calculate Minimal Changes: React identifies the exact differences (e.g., "this text changed", "this button was added").
  4. 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

AspectReal DOMVirtual DOM
NatureBrowser API objectPlain JavaScript object
Update SpeedSlow (reflows, repaints)Fast (just memory operations)
UpdatesDirectly manipulates UIUpdates in memory, then syncs minimal changes
MemoryHigher overheadLightweight

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

JSX// A simple counter SPA built with React import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // state return ( <div> <h1>Current Count: {count}</h1> <button onClick={() => setCount(count + 1)}> Increment </button> </div> ); } export default Counter;

What happens when you click the button?

  1. setCount updates the state.
  2. React creates a new Virtual DOM with count = 1.
  3. React diffs old VDOM (count=0) vs. new VDOM (count=1). It finds the <h1> text changed.
  4. React updates only that one text node in the Real DOM.
  5. No page reload. The UI updates instantly (SPA behavior).

7. Summary Cheat Sheet

ConceptOne-Line Summary
ReactA library for building UI components.
ComponentA reusable, self-contained piece of UI.
JSXHTML-like syntax inside JavaScript.
Virtual DOMA lightweight copy of the real DOM used for efficient updates.
DiffingComparing old and new Virtual DOM to find changes.
ReconciliationThe process of updating only changed parts of the real DOM.
SPAA web app that loads a single HTML page and updates dynamically without reloads.
StateData that changes over time within a component.
PropsData passed from a parent to a child component.

React MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic React MCQs

1

What is React?

AA database system
BA JavaScript library for building UIs
CA CSS framework
DAn operating system
Explanation: React is an open-source JavaScript library focused on building user interfaces with components.
2

Who originally created React?

AGoogle
BFacebook (Meta)
CMicrosoft
DAmazon
Explanation: React was created by Facebook engineers and released in 2013.
3

What is JSX?

AA separate HTML templating engine
BA CSS preprocessor
CA JavaScript syntax extension for UI markup
DA package manager
Explanation: JSX lets you write HTML-like syntax inside JavaScript, which React transforms into render calls.
4

SPA stands for:

ASimple Page App
BSingle Page Application
CServer Page Architecture
DStatic Page App
Explanation: SPAs load once and update content dynamically without full page reloads.
5

The Virtual DOM is:

AA browser plugin
BA lightweight JavaScript representation of the real DOM
CA React Router feature
DA CSS engine
Explanation: React compares Virtual DOM trees to minimize expensive real DOM updates.
6

Data passed from parent to child component is called:

Astate
Bprops
Ccontext only
Dreducers
Explanation: Props are read-only inputs passed down the component tree.
7

useState returns:

AOnly a value
BAn array with value and setter function
CA Promise
DA DOM node
Explanation: const [count, setCount] = useState(0) is the common destructuring pattern.
8

When component state changes, React:

AReloads the entire browser page
BRe-renders and reconciles UI changes efficiently
COnly updates CSS files
DStops JavaScript execution
Explanation: React triggers a re-render, diffs Virtual DOM, and updates only changed real DOM nodes.
9

React is best described as a:

AFull MVC framework
BView/UI library
CBackend API framework
DDatabase ORM
Explanation: React focuses on the view layer; routing and global state often come from additional libraries.
10

To add React to an existing project, you typically run:

Anpm install react react-dom
Bnpm get react
Cnode install react
Dreact init app
Explanation: Core packages are react and react-dom for rendering to the browser.

10 Advanced React MCQs

1

What is reconciliation in React?

AAPI response caching
BUpdating the real DOM based on Virtual DOM diff
CClient-side routing only
DUnit testing strategy
Explanation: Reconciliation is React's process of applying minimal DOM updates after diffing Virtual DOM trees.
2

useEffect runs after:

AServer startup
BRender is committed to the screen
CBefore the component function is defined
DNever in functional components
Explanation: Effects run after paint by default, useful for side effects like fetching data or subscriptions.
3

The key prop in lists helps React:

AApply CSS styles
BIdentify which items changed, were added, or removed
CImprove SEO ranking
DEnable routing
Explanation: Stable unique keys improve list reconciliation accuracy and prevent UI bugs.
4

A controlled component means:

AForm input value is driven by React state
BComponent has no state
CServer controls all inputs
DCSS controls input values
Explanation: In controlled inputs, React state is the single source of truth for the input value.
5

React.Fragment is used to:

AGroup elements without adding extra DOM nodes
BSplit bundles automatically
CReplace useState
DLazy-load images only
Explanation: Fragments let you return multiple elements without wrapping them in an extra <div>.
6

One-way data binding in React helps because:

AIt removes the need for state
BData flow is predictable and easier to debug
CBrowsers require it
DIt disables re-rendering
Explanation: Props flow down; state changes trigger re-renders in a clear, traceable direction.
7

createRoot from react-dom/client is used to:

ACompile CSS
BMount a React 18 app to a DOM element
CRun Jest tests
DConfigure React Router
Explanation: createRoot(document.getElementById('root')).render(<App />) is the modern entry pattern.
8

"Lifting state up" means:

AMoving shared state to a common ancestor component
BUsing global variables everywhere
CDeleting component state
DStoring state only in localStorage
Explanation: When siblings need the same data, state is moved up and passed down via props.
9

Conditional rendering in JSX commonly uses:

ASQL queries
BTernary operator or logical &&
CHTML imports only
DCSS @media inside JSX
Explanation: Examples: {isLoggedIn ? <Dashboard /> : <Login />} or {error && <p>{error}</p>}.
10

React Strict Mode helps developers by:

AMinifying production bundles
BHighlighting potential problems during development
CReplacing React Router
DDisabling hooks
Explanation: Strict Mode runs extra checks (like detecting unsafe lifecycles) to catch issues early.

15 Interview Questions & Answers

Easy Medium Hard
1What is React?easy
Answer: React is an open-source JavaScript library for building user interfaces using reusable components. It focuses on the view layer and is widely used for SPAs and interactive web apps.
2Is React a library or a framework?easy
Answer: React is a library, not a full framework. It handles UI rendering; you typically add routing (React Router), state management (Redux/Context), and data fetching libraries separately.
3What is JSX and why use it?easy
Answer: JSX is a syntax extension that looks like HTML inside JavaScript. It makes component UI code more readable and expressive, and compiles to React.createElement calls.
4Explain the Virtual DOM.medium
Answer: The Virtual DOM is an in-memory JavaScript representation of the UI. When state changes, React builds a new Virtual DOM tree, diffs it with the previous one, and updates only the changed parts of the real DOM (reconciliation).
5What is a Single Page Application (SPA)?easy
Answer: An SPA loads one HTML page initially and updates content dynamically via JavaScript without full page reloads. React is commonly used to build SPAs with fast, app-like navigation.
6What is the difference between props and state?medium
Answer: Props are read-only data passed from parent to child. State is mutable data managed inside a component (via useState) that triggers re-renders when updated.
7What are React Hooks?medium
Answer: Hooks are functions like useState, useEffect, and useContext that let functional components use state, side effects, and other React features without class components.
8When do you use useState vs useEffect?medium
Answer: useState stores data that changes over time inside a component. useEffect runs side effects after render—API calls, subscriptions, timers, or syncing with external systems.
9What is reconciliation?medium
Answer: Reconciliation is React's algorithm for comparing the new Virtual DOM with the previous one and applying the minimal set of changes to the real DOM efficiently.
10Controlled vs uncontrolled components?medium
Answer: Controlled components store form values in React state (value + onChange). Uncontrolled components keep values in the DOM and are accessed via refs—useful for simple forms or file inputs.
11Why are keys important in lists?medium
Answer: Keys help React identify list items across renders. Using stable unique keys (not array index when items reorder) prevents incorrect DOM reuse and state bugs.
12What is "lifting state up"?medium
Answer: When two or more components need the same state, move that state to their closest common parent and pass it down as props along with updater callbacks.
13What is one-way data binding in React?medium
Answer: Data flows downward via props from parent to child. Child components notify parents of changes through callback functions, making data flow predictable and easier to trace.
14React vs Angular — key difference?hard
Answer: React is a flexible UI library with an ecosystem of optional tools. Angular is a full opinionated framework with built-in routing, forms, HTTP, and DI—steeper learning curve but more structure out of the box.
15How do you optimize React performance?hard
Answer: Use 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.