React Master Course
The complete deep-explanation guide to React — from "Why React?" all the way to performance, architecture, and interview preparation.
🎮 What You’ll Master
- ✓ Every file in a React project — explained in detail
- ✓ Why React dominates the frontend
- ✓ Core concepts from beginner to expert
- ✓ How React renders (phases, reconciliation, Fiber)
- ✓ useEffect deep internals
- ✓ Folder structures & architecture patterns
- ✓ Performance optimization & interview prep
Project Files Explained
package.json, node_modules, configs & more
1️⃣Why Choose React?
Component architecture, Virtual DOM, ecosystem
2️⃣Complete React Concepts
Beginner → Expert skill levels
3️⃣React Phases
Render Phase & Commit Phase
4️⃣How useEffect Works
Dependencies, cleanup, internal flow
5️⃣Reconciliation
Diffing algorithm & keys
6️⃣Folder Structures
Simple → Enterprise architecture
7️⃣Course Structure
10 modules from fundamentals to system design
8️⃣Rendering Types
CSR, SSR, SSG, ISR
9️⃣React Lifecycle
Mount, Update, Unmount
🔟Performance Rules
useMemo, useCallback, React.memo
🎯Interview Questions
Critical concepts for interviews
Every File in a React Project — Explained
When you open a React project (created with Create React App or Vite), you see a bunch of files and folders. Here’s what each one does, why it exists, and what happens if you delete it.
These files manage your project's dependencies and scripts.
📊 File Importance at a Glance
🔴 Critical — App breaks without these
🟡 Important — Major features break
🟢 Standard — Nice to have, recreatable
🧠 Quick Quiz
You cloned a React repo but forgot to run 'npm install'. Which of these WILL exist?
Why Choose React?
Building a website with React is like building a house using LEGO blocks.
Reusable
Build once, use everywhere
Independent
Each component is self-contained
Maintainable
Easy to update without breaking others
// Each "block" is a component
function Button({ label, color }) {
return (
<button className={`px-4 py-2 rounded ${color}`}>
{label}
</button>
);
}
// Reuse it anywhere!
<Button label="Sign Up" color="bg-blue-500" />
<Button label="Login" color="bg-green-500" />
<Button label="Cancel" color="bg-red-500" />React doesn't repaint the whole wall. It compares old vs new UI and only updates what changed.
🎨 Real-Life Analogy
Before painting, you compare the old photo and the new photo → you only fix the areas that changed. React does exactly this with the DOM!
❌ Without Virtual DOM
Re-render entire page → Slow, flickering, wasteful
✅ With Virtual DOM
Compare & patch only changes → Fast, smooth, efficient
Routing
React Router, Next.js
State Management
Redux, Zustand, Jotai
Form Libraries
React Hook Form, Formik
DevTools
React DevTools, Profiler
Community
Largest frontend community
UI Libraries
MUI, Chakra, Shadcn
Instead of saying HOW to update UI, you say WHAT UI should look like.
❌ Imperative (Vanilla JS)
// You manually tell the browser
// each step to update the DOM
const el = document.getElementById("app");
el.innerHTML = "";
const h1 = document.createElement("h1");
h1.textContent = "Hello World";
h1.style.color = "blue";
el.appendChild(h1);✅ Declarative (React)
// You describe WHAT the UI should be
// React figures out HOW to update it
function App() {
return (
<h1 style={{ color: "blue" }}>
Hello World
</h1>
);
}5. Job Market Dominance
React dominates the frontend job market worldwide.
70%+
Frontend job listings mention React
#1
Most used frontend library
200K+
npm weekly downloads (millions)
🧠 Quick Quiz
What is the biggest advantage of React's Virtual DOM?
Complete React Concepts (Beginner → Expert)
Core Basics
JSX
JavaScript XML — write HTML inside JS
Components
Reusable building blocks of UI
Props
Pass data from parent to child
State
Internal data that changes over time
Event Handling
onClick, onChange, onSubmit
Conditional Rendering
Show/hide based on conditions
List Rendering
Map arrays to JSX elements
Keys
Unique identifiers for list items
// JSX + Component + Props + State + Events
import { useState } from 'react';
function Counter({ initialCount }) { // Props
const [count, setCount] = useState(initialCount); // State
return (
<div>
{/* JSX — HTML in JavaScript */}
<h1>Count: {count}</h1>
{/* Event Handling */}
<button onClick={() => setCount(count + 1)}>+1</button>
{/* Conditional Rendering */}
{count > 10 && <p>🎉 You passed 10!</p>}
</div>
);
}
// List Rendering with Keys
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li> {/* Key! */}
))}
</ul>
);
}Hooks & Side Effects
useState
Manage local state in components
useEffect
Run side effects (API calls, timers)
useRef
Access DOM elements & persist values
useContext
Share data without prop drilling
Custom Hooks
Extract reusable logic
import { useState, useEffect, useRef, useContext, createContext } from 'react';
// ── useEffect: fetch data on mount ──
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, [userId]); // re-runs when userId changes
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
// ── useRef: focus input on mount ──
function SearchBar() {
const inputRef = useRef(null);
useEffect(() => { inputRef.current.focus(); }, []);
return <input ref={inputRef} placeholder="Search..." />;
}
// ── Custom Hook: reusable logic ──
function useLocalStorage(key, initial) {
const [value, setValue] = useState(
() => JSON.parse(localStorage.getItem(key)) ?? initial
);
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}Advanced Rendering
import { memo, useMemo, useCallback } from 'react';
// React.memo — skip re-render if props didn't change
const ExpensiveList = memo(function ExpensiveList({ items }) {
console.log("Rendering list...");
return items.map(item => <div key={item.id}>{item.name}</div>);
});
// useMemo — cache expensive calculation
function Dashboard({ orders }) {
const total = useMemo(() => {
console.log("Calculating total...");
return orders.reduce((sum, o) => sum + o.price, 0);
}, [orders]); // only recalculate when orders change
return <h2>Total: ${total}</h2>;
}
// useCallback — stable function reference
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Clicked!");
}, []); // same function reference across renders
return <ExpensiveList onClick={handleClick} />;
}Architecture
Production
import { lazy, Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
// ── Lazy Loading + Code Splitting ──
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
// ── Error Boundary ──
function App() {
return (
<ErrorBoundary fallback={<p>Something went wrong 💥</p>}>
<Suspense fallback={<p>Loading...</p>}>
<Dashboard />
</Suspense>
</ErrorBoundary>
);
}🧠 Quick Quiz
Which level covers useMemo, useCallback, and React.memo?
React Phases (Very Important)
React has 2 main phases. Understanding them is critical for performance and debugging.
Render Phase
React calculates what UI SHOULD look like.
- ▸ Calls component function
- ▸ Reads state & props
- ▸ Creates Virtual DOM
- ▸ Compares with previous Virtual DOM (Diffing)
⚠️ NO DOM changes happen here!
🏗️ Real Life Mapping:
Architect designs the blueprint. No construction yet.
Commit Phase
React applies changes to the real DOM.
- ▸ DOM updates applied
- ▸ useLayoutEffect runs (sync)
- ▸ Browser paints screen
- ▸ useEffect runs (async)
✅ This is where real DOM gets updated!
🏗️ Real Life Mapping:
Construction workers build according to blueprint.
🔄 Complete Flow
🧠 Quick Quiz
During which phase does React create and compare Virtual DOM?
How useEffect Really Works
useEffect(() => {
// Effect logic (runs AFTER paint)
return () => {
// Cleanup (runs before next effect or unmount)
};
}, [dependencies]); // Controls WHEN it runs[]Empty ArrayRuns only once after first commit (like componentDidMount)
useEffect(() => {
console.log("Runs once on mount!");
fetchInitialData();
}, []); // ← empty array = run once[value]With DependenciesRuns when value changes
useEffect(() => {
console.log("userId changed:", userId);
fetchUser(userId);
}, [userId]); // ← re-runs when userId changesRuns after every render (usually you don't want this!)
useEffect(() => {
console.log("Runs after EVERY render!");
}); // ← no array = runs every timeRender Phase completes
Commit Phase updates DOM
React schedules useEffect
Browser paints UI to screen
useEffect runs (async, after paint)
useEffect does NOT block the UI. It runs asynchronously after the browser paints.
Cleanup runs:
- ▸ Before the next effect execution
- ▸ On component unmount
useEffect(() => {
// Start a timer
const interval = setInterval(() => {
console.log("Running every second...");
}, 1000);
// Cleanup: stop the timer
return () => {
clearInterval(interval); // Prevents memory leak!
console.log("Timer cleaned up ✅");
};
}, []);
// WHY cleanup?
// Without it, the timer keeps running even
// after the component is removed from screen
// → MEMORY LEAK! 💥🧠 Quick Quiz
When does useEffect's cleanup function run?
React Reconciliation
Reconciliation = React's diffing algorithm. It's how React figures out what changed.
📋 Steps:
Compare previous Virtual DOM tree
Compare new Virtual DOM tree
Find differences (diff)
Update only changed nodes in real DOM
🔑 Why Keys Are Critical
❌ Without Keys
// React can't track items properly
// May re-render ALL items or mix up state!
{items.map(item => (
<Card>{item.name}</Card>
))}✅ With Keys
// React tracks each item by unique key
// Only re-renders items that changed!
{items.map(item => (
<Card key={item.id}>{item.name}</Card>
))}id instead.🧠 Quick Quiz
What happens if you don't use keys in a list?
Complete Folder Structures
Small Apps & Learning Projects
src/
├── components/ # Reusable UI components
│ ├── Button.jsx
│ ├── Header.jsx
│ └── Footer.jsx
├── pages/ # Route-level components
│ ├── Home.jsx
│ └── About.jsx
├── App.jsx # Main app component
└── main.jsx # Entry point✅ Good for small apps, learning, and quick prototypes.
Scalable Apps
src/
├── features/ # Grouped by feature
│ ├── auth/
│ │ ├── components/ # Auth-specific UI
│ │ ├── hooks/ # Auth hooks
│ │ ├── services/ # Auth API calls
│ │ └── authSlice.js # Auth state
│ ├── dashboard/
│ │ ├── components/
│ │ ├── hooks/
│ │ └── dashboardSlice.js
│ └── users/
│
├── shared/ # Shared across features
│ ├── components/ # Button, Modal, Input...
│ ├── utils/ # formatDate, capitalize...
│ └── hooks/ # useDebounce, useLocalStorage...
│
├── routes/ # Route configuration
├── App.jsx
└── main.jsx✅ Best for scalability. Each feature is self-contained and easy to maintain.
Large SaaS Systems
src/
├── app/ # App initialization, providers
├── modules/ # Business logic modules
├── services/ # External service integrations
├── api/ # API client & endpoints
├── store/ # Global state management
├── layouts/ # Page layouts (DashboardLayout, AuthLayout)
├── constants/ # App-wide constants
├── config/ # Environment & feature configs
├── hooks/ # Global custom hooks
├── utils/ # Helper functions
├── types/ # TypeScript type definitions
├── routes/ # Route definitions & guards
└── components/ # Shared UI components✅ Used in large SaaS systems with multiple teams working on different modules.
Complete Course Structure (10 Modules)
This is the full learning roadmap — from absolute beginner to production-ready.
Fundamentals
Hooks
Routing
State Management
Performance
Architecture
Authentication
Testing
Production Optimization
System Design
React Rendering Types
🖥️ CSR
Client-Side Rendering
- ▸ Browser downloads empty HTML + JS bundle
- ▸ JS runs and builds the page in browser
- ▸ Used by: Create React App, Vite
🌐 SSR
Server-Side Rendering
- ▸ Server builds full HTML for each request
- ▸ Sends complete page to browser
- ▸ Used by: Next.js (getServerSideProps)
📄 SSG
Static Site Generation
- ▸ Pages built at build time (once)
- ▸ Served as static HTML from CDN
- ▸ Used by: Next.js (getStaticProps), Astro
🔄 ISR
Incremental Static Regeneration
- ▸ SSG + auto-rebuild after a time interval
- ▸ Best of both: static speed + fresh data
- ▸ Used by: Next.js (revalidate)
🧠 Quick Quiz
Which rendering type pre-builds pages at build time and serves them from a CDN?
React Lifecycle (Function Components)
Mount
Component appears on screenUpdate
State or props changeUnmount
Component removed from screenfunction LifecycleDemo() {
const [count, setCount] = useState(0);
// MOUNT: runs once
useEffect(() => {
console.log("🟢 Mounted!");
// UNMOUNT: cleanup
return () => console.log("🔴 Unmounted!");
}, []);
// UPDATE: runs when count changes
useEffect(() => {
console.log("🔵 Count updated to:", count);
return () => console.log("🧹 Cleaning up previous count effect");
}, [count]);
return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>;
}
// Console output when clicking 3 times:
// 🟢 Mounted!
// 🔵 Count updated to: 0
// 🧹 Cleaning up previous count effect
// 🔵 Count updated to: 1
// 🧹 Cleaning up previous count effect
// 🔵 Count updated to: 2
// 🧹 Cleaning up previous count effect
// 🔵 Count updated to: 3Performance Rules
❌ Avoid These Mistakes
1. Unnecessary State
// ❌ Derived data in state
const [items, setItems] = useState([...]);
const [count, setCount] = useState(items.length);
// count is derived from items — don't put it in state!// ✅ Derive it directly
const [items, setItems] = useState([...]);
const count = items.length;
// No extra state needed!2. Inline Functions in Heavy Components
// ❌ New function every render
<ExpensiveList
onSort={() => sort(items)} // new ref each time!
/>// ✅ Stable function with useCallback
const handleSort = useCallback(
() => sort(items), [items]
);
<ExpensiveList onSort={handleSort} />3. Re-creating Objects Every Render
// ❌ New object every render
<MyComponent style={{ color: 'red' }} />
// { color: 'red' } !== { color: 'red' }// ✅ Memoize or define outside
const style = useMemo(
() => ({ color: 'red' }), []
);
<MyComponent style={style} />✅ Use These Tools
useMemo
Cache expensive calculations
const total = useMemo(() => calc(data), [data])useCallback
Stable function references
const fn = useCallback(() => {...}, [deps])React.memo
Skip re-render if props unchanged
const Comp = memo(function Comp(props) {...})Proper Keys
Help React track list items
<Item key={item.id} />🧠 Quick Quiz
What's the problem with const [count, setCount] = useState(items.length)?
Interview Critical Questions
These are the most asked React interview questions. Master these and you'll stand out.
1What is the Virtual DOM?
A lightweight JavaScript representation of the real DOM. React creates a virtual copy, compares it with the previous version (diffing), and only updates the changed parts in the real DOM. This makes updates efficient and fast.
2Explain Reconciliation.
Reconciliation is React's diffing algorithm. When state changes, React creates a new Virtual DOM tree, compares it with the old one, identifies the minimal set of changes, and applies them to the real DOM.
3What triggers a re-render?
1) setState/useState setter called, 2) Parent component re-renders (unless using React.memo), 3) Context value changes, 4) forceUpdate (class components).
4useEffect vs useLayoutEffect?
useEffect runs asynchronously AFTER browser paint — won't block UI. useLayoutEffect runs synchronously BEFORE browser paint — can block UI but useful for DOM measurements/mutations before user sees the screen.
5How does React Batching work?
React groups multiple setState calls into a single re-render for performance. In React 18+, all updates are automatically batched — even inside setTimeout, promises, and event handlers.
6What is React Fiber?
Fiber is React's internal reconciliation engine (since React 16). It breaks rendering work into small units called "fibers", allowing React to pause, prioritize, and resume work — enabling concurrent rendering.
7Why are keys important?
Keys help React identify which items in a list changed, were added, or removed. Without proper keys, React can't efficiently diff lists and may mix up component state or do unnecessary DOM operations.
8When should you optimize?
Profile first! Use React DevTools Profiler to find actual bottlenecks. Don't prematurely optimize — useMemo/useCallback/React.memo have their own cost. Optimize only when you measure a real performance issue.
Don't just memorize answers — understand the WHY behind each concept. Interviewers can tell the difference between memorization and deep understanding.