๐Ÿš€ React Foundations

Modern JavaScript aur React ke saath apni web development journey shuru karo!

๐Ÿ“š React Kya Hai?

React ek JavaScript library hai jo user interfaces (UI) banane ke liye use hoti hai. Facebook (Meta) ne isko 2013 mein create kiya tha.

๐ŸŽฏ React Ko Kyun Use Karein?

  • Component-Based: Chhote chhote reusable pieces mein code likho
  • Virtual DOM: Fast aur efficient updates
  • Declarative: UI ko describe karo, React baaki sambhal lega
  • Learn Once, Write Anywhere: Web, Mobile (React Native), Desktop sab jagah
  • Huge Community: Lakhon developers ka support
React Example Dekho

๐ŸŒ SPA vs MPA

๐Ÿ“„ SPA (Single Page Application)

Definition: A web application that loads a single HTML page and dynamically updates content.


Explanation: Ek hi page load hota hai initially, phir JavaScript dynamically content update karta hai. Page reload nahi hota!

  • โœ… Fast navigation
  • โœ… Better UX
  • โœ… Less server load
  • โŒ Initial load time thoda zyada
  • โŒ SEO challenges

๐Ÿ“‘ MPA (Multi Page Application)

Definition: A web application with multiple HTML pages that reload on navigation.


Explanation: Har page ke liye alag HTML file. Jab navigate karo, pura page reload hota hai.

  • โœ… Better SEO naturally
  • โœ… Simpler architecture
  • โœ… Easier to start
  • โŒ Slower navigation
  • โŒ More server requests

๐ŸŽจ Virtual DOM vs Real DOM

๐ŸŒณ Real DOM

Actual browser ka DOM tree

Heavy aur slow updates

โ†’

โšก Virtual DOM

React ka lightweight copy

Fast aur efficient

๐Ÿ”„ Kaise Kaam Karta Hai?

  1. Step 1: React Virtual DOM ka snapshot banata hai (memory mein)
  2. Step 2: Jab state change hoti hai, naya Virtual DOM banta hai
  3. Step 3: React dono ko compare karta hai (Diffing Algorithm)
  4. Step 4: Sirf changes ko Real DOM mein update karta hai (Reconciliation)
// Real DOM - Slow document.getElementById('title').innerHTML = 'New Title'; document.getElementById('text').innerHTML = 'New Text'; // Har change pe browser repaint karta hai! // React Virtual DOM - Fast setState({ title: 'New Title', text: 'New Text' }); // React smartly sirf zaruri changes apply karega!

๐Ÿงต React Fiber Architecture

React Fiber React ki reimplementation hai jo React 16 mein introduce hui. Ye reconciliation algorithm ka naya implementation hai.

๐ŸŽฏ Fiber Kya Solve Karta Hai?

Problem: Purane React mein, agar koi bada update ho raha ho, to browser freeze ho jata tha. User interactions (clicks, typing) block ho jate the.


Solution: Fiber kaam ko chhote pieces mein tod deta hai aur priority ke according karta hai.

โœจ Key Features:

  • Incremental Rendering: Kaam ko pause kar sakte ho aur baad mein resume
  • Priority-based Updates: Important updates pehle (animations > data fetching)
  • Concurrency: Multiple tasks ek saath prepare ho sakte hain
  • Error Boundaries: Better error handling
// Fiber ka internal structure (simplified) const fiber = { type: 'div', // Component type key: 'unique-key', // Unique identifier props: { className: 'box' }, // Props child: null, // First child fiber sibling: null, // Next sibling fiber return: null, // Parent fiber alternate: null, // Previous version effectTag: 'UPDATE' // What to do (UPDATE/DELETE/PLACE) };

๐Ÿš€ React 18 Ke Naye Features

1๏ธโƒฃ Concurrent Rendering

Definition: React can work on multiple tasks at once and prioritize them.

React ab multiple UI updates ko ek saath prepare kar sakta hai aur urgent updates ko priority de sakta hai.

2๏ธโƒฃ Automatic Batching

Definition: Multiple state updates are grouped together for a single re-render.

React 18 se pehle sirf event handlers mein batching hoti thi. Ab promises, setTimeout, native events mein bhi hoti hai!

// React 18 - Automatically batched! setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); // Sirf ek re-render! ๐ŸŽ‰ }, 1000);

3๏ธโƒฃ Transitions API

Definition: Mark certain updates as non-urgent transitions.

Kuch updates ko "non-urgent" mark kar sakte ho, taki user interaction smooth rahe.

import { startTransition } from 'react'; // Urgent: user input setInputValue(input); // Non-urgent: search results startTransition(() => { setSearchResults(data); });

4๏ธโƒฃ Suspense for Data Fetching

Definition: Declaratively specify loading states for components.

Ab data fetch karte waqt loading UI dikhana bahut easy hai!

5๏ธโƒฃ New Root API

// React 17 ReactDOM.render(<App />, document.getElementById('root')); // React 18 const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />);

๐Ÿงฉ Component-Based Architecture

Components are reusable, independent pieces of UI. Har component apna logic aur appearance manage karta hai.

App Component
Header
Main Content
Footer
Nav
Logo
Article
Sidebar

๐ŸŽ Benefits:

  • Reusability: Ek baar likho, kahin bhi use karo
  • Maintainability: Chhote pieces ko maintain karna easy hai
  • Testing: Individual components ko test karna simple
  • Collaboration: Team mein alag alag components pe kaam ho sakta hai
// Simple Component Example function Button({ text, onClick }) { return ( <button onClick={onClick}> {text} </button> ); } // Usage - Reusable hai! <Button text="Submit" onClick={handleSubmit} /> <Button text="Cancel" onClick={handleCancel} />

โš™๏ธ Development Environment Setup

๐Ÿ“ฆ Required Tools:

  1. Node.js & npm: JavaScript runtime aur package manager
  2. Code Editor: VS Code (recommended)
  3. Build Tool: Vite / Create React App / Next.js

โšก Vite (Recommended)

Extremely fast build tool

  • Lightning fast HMR
  • Instant server start
  • Optimized builds
npm create vite@latest my-app -- --template react cd my-app npm install npm run dev

๐Ÿ“ฆ Create React App

Traditional, zero-config setup

  • All-in-one solution
  • Production-ready
  • Slower than Vite
npx create-react-app my-app cd my-app npm start

๐Ÿ”Œ VS Code Extensions:

  • ES7+ React/Redux/React-Native snippets - Quick code snippets
  • Prettier - Code formatting
  • ESLint - Code quality
  • Auto Rename Tag - Rename paired tags
  • Bracket Pair Colorizer - Better code readability

๐Ÿ” Behind The Scenes - React Kaise Render Karta Hai?

๐Ÿ“ Rendering Process (Step by Step):

  1. Trigger: Initial render ya state/props change
  2. Render Phase: React components ko call karta hai aur Virtual DOM tree banata hai
  3. Reconciliation: Purane aur naye Virtual DOM ko compare karta hai
  4. Commit Phase: Changes ko Real DOM mein apply karta hai
  5. Browser Paint: Browser screen ko update karta hai
// 1. Component function call hota hai function Counter() { const [count, setCount] = useState(0); // 2. JSX return hota hai (React.createElement calls) return <div>{count}</div>; } // 3. React internally ye banata hai: React.createElement('div', null, count); // 4. Virtual DOM node banta hai: { type: 'div', props: { children: 0 } } // 5. Reconciliation ke baad Real DOM update hota hai

๐Ÿ’ผ Interview Questions

Click on questions to see answers!

Q1. React kya hai aur iske main features kya hain? Easy

Answer: React ek JavaScript library hai jo user interfaces banane ke liye use hoti hai. Main features:

  • Component-Based: UI ko reusable pieces mein divide karte hain
  • Virtual DOM: Efficient updates ke liye
  • Declarative: UI ki final state describe karte hain, React baaki sambhal leta hai
  • JSX: HTML-like syntax JavaScript mein
  • One-way Data Flow: Data parent se child ki taraf flow hota hai
Q2. Virtual DOM kya hai aur ye Real DOM se fast kyun hai? Easy

Answer: Virtual DOM React ka lightweight JavaScript representation hai Real DOM ka. Ye fast hai kyunki:

  • Ye memory mein rehta hai, browser paint nahi karta
  • React diffing algorithm se sirf actual changes find karta hai
  • Batch updates - multiple changes ko ek saath apply karta hai
  • Real DOM manipulation expensive hai (reflow, repaint), Virtual DOM mein ye nahi hota
  • Efficient reconciliation process se minimum DOM updates hote hain
Q3. SPA aur MPA mein kya difference hai? React kis type ka application hai? Medium

Answer:

SPA (Single Page Application): Ek hi HTML page load hota hai, content dynamically update hota hai JavaScript se. Page reload nahi hota. Better UX but SEO challenges.

MPA (Multi Page Application): Multiple HTML pages hain, har navigation pe new page load hota hai. Better SEO but slower navigation.

React primarily SPAs banane ke liye use hota hai, lekin Next.js jaise frameworks ke saath Server-Side Rendering bhi kar sakte hain jo SPA aur MPA ke benefits combine karta hai.

Q4. React Fiber kya hai aur isko introduce kyun kiya gaya? Medium

Answer: React Fiber React 16 mein introduce hua reimplementation hai reconciliation algorithm ka. Main goals:

  • Incremental Rendering: Rendering work ko chunks mein split kar sakte hain aur pause/resume kar sakte hain
  • Priority-based Updates: Different updates ko different priority assign kar sakte hain (animations high priority, data fetching low)
  • Concurrency: Multiple versions of UI ko parallel prepare kar sakte hain
  • Better Error Handling: Error boundaries se graceful error handling

Purane version mein long-running updates browser ko block kar dete the. Fiber ne ye problem solve kari.

Q5. React 18 ke main features kya hain? Concurrency kya hai? Hard

Answer: React 18 ke main features:

  • Automatic Batching: Promises, setTimeout mein bhi automatic batching
  • Transitions API: Non-urgent updates ko mark kar sakte hain using startTransition
  • Suspense for Data Fetching: Declarative loading states
  • New Root API: createRoot for concurrent features
  • Streaming SSR: Server-side rendering improvements

Concurrency: React ka ability multiple UI versions ko ek saath prepare karna. Main thread ko block nahi karta, urgent updates ko priority deta hai. Example: typing (urgent) aur search results update (non-urgent) ko alag handle karta hai.

Q6. Component-based architecture ke kya benefits hain? Explain with example. Medium

Answer: Component-based architecture ke benefits:

  • Reusability: Components ko multiple jagah use kar sakte hain
  • Maintainability: Isolated components ko maintain karna easy
  • Testability: Individual components ka testing simple
  • Scalability: Large applications ko organize karna easy
  • Separation of Concerns: Har component apni responsibility handle karta hai

Example: Ek Button component banao jo multiple forms mein reuse ho. Props se customization (color, size, text) control karo. Ek jagah change karo, sab jagah reflect ho.

Q7. React mein rendering process ko detail mein explain karo. Reconciliation kya hai? Hard

Answer: React Rendering Process:

  1. Trigger Phase: Initial mount ya setState/props change se render trigger hota hai
  2. Render Phase: React component functions ko call karta hai, JSX ko React elements mein convert karta hai, aur Virtual DOM tree bana
  3. Reconciliation Phase: Previous Virtual DOM aur new Virtual DOM ko compare karta hai (Diffing Algorithm). Ye phase pure hai aur side-effects nahi hote
  4. Commit Phase: Actual DOM mutations apply hote hain. useEffect/useLayoutEffect yahan run hote hain
  5. Browser Paint: Browser updated UI display karta hai

Reconciliation: Ye process hai jismein React efficiently determine karta hai ki DOM mein kya changes chahiye. React keys aur element types use karke optimize karta hai. Fiber architecture isko interruptible banata hai.