Press ESC to close
⚛️ React🧠 Deep Dive🚀 Master Course

React Master Course

The complete deep-explanation guide to React — from "Why React?" all the way to performance, architecture, and interview preparation.

👨‍💻safal.me

🎮 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
📁

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

package.jsonsrc/App.jsindex.jsindex.html

🟡 Important — Major features break

package-lock.jsonnode_modules/components/public/.gitignore

🟢 Standard — Nice to have, recreatable

README.md

🧠 Quick Quiz

You cloned a React repo but forgot to run 'npm install'. Which of these WILL exist?

1️⃣

Why Choose React?

🧩 1. Component-Based Architecture

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

Button.jsxjsx
// 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" />
⚡ 2. Virtual DOM (Performance)

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

🌐 3. Massive Ecosystem
🔀

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

📜 4. Declarative Programming

Instead of saying HOW to update UI, you say WHAT UI should look like.

❌ Imperative (Vanilla JS)

vanilla.jsjs
// 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)

App.jsxjsx
// 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?

2️⃣

Complete React Concepts (Beginner → Expert)

LEVEL 1

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

Level1-Example.jsxjsx
// 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>
  );
}
LEVEL 2

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

Level2-Hooks.jsxjsx
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];
}
LEVEL 3

Advanced Rendering

🔍Reconciliation
🖥️Virtual DOM
🧵React Fiber
Concurrent Rendering
📦Batching
🧠React.memo
💾useMemo
🔒useCallback
📋Memoization
Level3-Memoization.jsxjsx
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} />;
}
LEVEL 4

Architecture

Folder structure
Feature-based design
API Layer
State management
Authentication flow
Protected routes
Role-based access
LEVEL 5

Production

Error Boundaries
Code Splitting
Lazy Loading
Suspense
Performance Optimization
Testing
Accessibility
SEO
Level5-Production.jsxjsx
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?

3️⃣

React Phases (Very Important)

🔥 Key Concept:

React has 2 main phases. Understanding them is critical for performance and debugging.

1

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.

2

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

State ChangeRender PhaseVirtual DOM DiffCommit PhaseDOM UpdateBrowser PaintuseEffect

🧠 Quick Quiz

During which phase does React create and compare Virtual DOM?

4️⃣

How useEffect Really Works

useEffect-syntax.jsxjsx
useEffect(() => {
  // Effect logic (runs AFTER paint)

  return () => {
    // Cleanup (runs before next effect or unmount)
  };
}, [dependencies]); // Controls WHEN it runs
⏰ When Does It Run?
[]Empty Array

Runs only once after first commit (like componentDidMount)

once.jsxjsx
useEffect(() => {
  console.log("Runs once on mount!");
  fetchInitialData();
}, []);  // ← empty array = run once
[value]With Dependencies

Runs when value changes

deps.jsxjsx
useEffect(() => {
  console.log("userId changed:", userId);
  fetchUser(userId);
}, [userId]);  // ← re-runs when userId changes
no arrayNo Dependency Array

Runs after every render (usually you don't want this!)

every-render.jsxjsx
useEffect(() => {
  console.log("Runs after EVERY render!");
});  // ← no array = runs every time
🔬 Internal Flow (Step-by-Step)
1

Render Phase completes

2

Commit Phase updates DOM

3

React schedules useEffect

4

Browser paints UI to screen

5

useEffect runs (async, after paint)

⚡ Important:

useEffect does NOT block the UI. It runs asynchronously after the browser paints.

🧹 Cleanup Function

Cleanup runs:

  • Before the next effect execution
  • On component unmount
cleanup.jsxjsx
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?

5️⃣

React Reconciliation

Reconciliation = React's diffing algorithm. It's how React figures out what changed.

📋 Steps:

1

Compare previous Virtual DOM tree

2

Compare new Virtual DOM tree

3

Find differences (diff)

4

Update only changed nodes in real DOM

🔑 Why Keys Are Critical

❌ Without Keys

bad.jsxjsx
// React can't track items properly
// May re-render ALL items or mix up state!
{items.map(item => (
  <Card>{item.name}</Card>
))}

✅ With Keys

good.jsxjsx
// React tracks each item by unique key
// Only re-renders items that changed!
{items.map(item => (
  <Card key={item.id}>{item.name}</Card>
))}
⚠️ Never use array index as key if your list can be reordered, filtered, or items inserted. Use a unique id instead.

🧠 Quick Quiz

What happens if you don't use keys in a list?

6️⃣

Complete Folder Structures

SIMPLE

Small Apps & Learning Projects

project-structure/text
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.

FEATURE-BASED⭐ Recommended

Scalable Apps

project-structure/text
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.

ENTERPRISE

Large SaaS Systems

project-structure/text
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.

7️⃣

Complete Course Structure (10 Modules)

This is the full learning roadmap — from absolute beginner to production-ready.

🌱
MODULE 1

Fundamentals

🪝
MODULE 2

Hooks

🔀
MODULE 3

Routing

🗃️
MODULE 4

State Management

MODULE 5

Performance

🏛️
MODULE 6

Architecture

🔐
MODULE 7

Authentication

🧪
MODULE 8

Testing

🚀
MODULE 9

Production Optimization

🎯
MODULE 10

System Design

8️⃣

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
Fast interactionsBad SEO

🌐 SSR

Server-Side Rendering

  • ▸ Server builds full HTML for each request
  • ▸ Sends complete page to browser
  • ▸ Used by: Next.js (getServerSideProps)
Great SEOSlower TTFB

📄 SSG

Static Site Generation

  • ▸ Pages built at build time (once)
  • ▸ Served as static HTML from CDN
  • ▸ Used by: Next.js (getStaticProps), Astro
FastestGreat SEO

🔄 ISR

Incremental Static Regeneration

  • ▸ SSG + auto-rebuild after a time interval
  • ▸ Best of both: static speed + fresh data
  • ▸ Used by: Next.js (revalidate)
Fast + FreshScalable

🧠 Quick Quiz

Which rendering type pre-builds pages at build time and serves them from a CDN?

9️⃣

React Lifecycle (Function Components)

🟢

Mount

Component appears on screen
Component RendersCommit to DOMuseEffect runs
🔵

Update

State or props change
Re-renderCommit changesCleanup prev effectRun new effect
🔴

Unmount

Component removed from screen
Cleanup function runs
lifecycle-demo.jsxjsx
function 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: 3
🔟

Performance Rules

Avoid These Mistakes

1. Unnecessary State

bad.jsxjsx
// ❌ 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!
good.jsxjsx
// ✅ Derive it directly
const [items, setItems] = useState([...]);
const count = items.length;
// No extra state needed!

2. Inline Functions in Heavy Components

bad.jsxjsx
// ❌ New function every render
<ExpensiveList
  onSort={() => sort(items)}  // new ref each time!
/>
good.jsxjsx
// ✅ Stable function with useCallback
const handleSort = useCallback(
  () => sort(items), [items]
);
<ExpensiveList onSort={handleSort} />

3. Re-creating Objects Every Render

bad.jsxjsx
// ❌ New object every render
<MyComponent style={{ color: 'red' }} />
// { color: 'red' } !== { color: 'red' }
good.jsxjsx
// ✅ 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.

💡 Interview Tip:

Don't just memorize answers — understand the WHY behind each concept. Interviewers can tell the difference between memorization and deep understanding.