1. React क्या है?
React एक JavaScript library है जिसका use interactive user interfaces बनाने के लिए किया जाता है।
React application को छोटे-छोटे components में divide करता है।
function Welcome() {
return <h1>Hello React!</h1>;
}
React का basic idea:
UI = f(state)
मतलब:
State बदले → UI automatically update हो।
React क्यों popular है?
- Component-based architecture
- Reusable UI
- Declarative programming
- Fast updates
- Huge ecosystem
- React Native के साथ mobile development
- Next.js जैसे frameworks के साथ full-stack applications
- Large community
- Job market में strong demand
2. React सीखने का सही क्रम
JavaScript
↓
JSX
↓
Components
↓
Props
↓
Events
↓
State
↓
Conditional Rendering
↓
Lists + Keys
↓
Forms
↓
Hooks
↓
API Calls
↓
Context
↓
Custom Hooks
↓
Routing
↓
Performance
↓
Testing
↓
Production Architecture
Golden Rule
React सीखते समय सिर्फ syntax याद मत करो।
हर concept के साथ:
CONCEPT
↓
EXAMPLE
↓
PRACTICE
↓
CHALLENGE
↓
PROJECT
3. React Project Setup
Modern React project के लिए commonly used setup:
npm create vite@latest my-react-app
cd my-react-app
npm install
npm run dev
React install:
npm install react react-dom
Production build:
npm run build
Preview:
npm run preview
4. Basic React Structure
Typical project:
src/
├── components/
│ ├── Button.jsx
│ ├── Navbar.jsx
│ └── Card.jsx
│
├── pages/
│ ├── Home.jsx
│ └── About.jsx
│
├── hooks/
│ └── useFetch.js
│
├── services/
│ └── api.js
│
├── App.jsx
└── main.jsx
Large application:
src/
├── components/
├── features/
├── pages/
├── hooks/
├── services/
├── context/
├── utils/
├── assets/
├── routes/
└── App.jsx
5. JSX
JSX का मतलब JavaScript XML है।
const element = <h1>Hello World</h1>;
JavaScript expression:
const name = "Raj";
return <h1>Hello {name}</h1>;
Expression:
const age = 20;
return <p>Age: {age}</p>;
JavaScript:
const user = {
name: "Raj",
age: 22
};
return (
<div>
<h2>{user.name}</h2>
<p>{user.age}</p>
</div>
);
JSX में class
HTML:
<div class="box"></div>
React:
<div className="box"></div>
JSX attributes
<img src="/logo.png" alt="Logo" />
<button disabled={true}>
Submit
</button>
6. Components
React component एक JavaScript function होता है जो JSX return करता है.
function Header() {
return <header>My Website</header>;
}
Use:
function App() {
return (
<>
<Header />
<main>Hello</main>
</>
);
}
Component naming
Good:
function UserProfile() {}
function ProductCard() {}
function Navbar() {}
Avoid:
function userprofile() {}
Component names generally PascalCase में रखें।
7. Fragment
Extra <div> create करने की जरूरत नहीं:
<>
<h1>Hello</h1>
<p>Welcome</p>
</>
या:
<React.Fragment>
<h1>Hello</h1>
<p>Welcome</p>
</React.Fragment>
8. Props
Props parent से child component को data भेजने के लिए use होते हैं।
function User({ name }) {
return <h2>Hello {name}</h2>;
}
function App() {
return <User name="Raj" />;
}
Multiple props:
function Product({ name, price, category }) {
return (
<div>
<h2>{name}</h2>
<p>{category}</p>
<strong>₹{price}</strong>
</div>
);
}
Use:
<Product
name="Laptop"
price={50000}
category="Electronics"
/>
Props are read-only
Don’t do:
props.name = "New Name";
Props और state को directly mutate नहीं करना चाहिए. React इन्हें render के लिए immutable snapshots की तरह treat करता है.
9. children Prop
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
Use:
<Card>
<h2>Hello</h2>
<p>React is powerful.</p>
</Card>
10. Event Handling
HTML:
<button onclick="handleClick()">
React:
<button onClick={handleClick}>
Example:
function App() {
const handleClick = () => {
console.log("Clicked");
};
return <button onClick={handleClick}>Click</button>;
}
Inline:
<button onClick={() => console.log("Clicked")}>
Click
</button>
Input:
<input onChange={(e) => console.log(e.target.value)} />
Common events:
onClick
onChange
onSubmit
onFocus
onBlur
onKeyDown
onKeyUp
onMouseEnter
onMouseLeave
11. State – useState
State component की changing information को store करता है।
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>
+
</button>
</>
);
}
Syntax:
const [state, setState] = useState(initialValue);
Examples:
const [name, setName] = useState("");
const [age, setAge] = useState(20);
const [isOpen, setIsOpen] = useState(false);
const [users, setUsers] = useState([]);
12. Functional State Updates
अगर नया state previous state पर depend करता है:
setCount(prev => prev + 1);
Better:
setCount(prev => prev + 1);
Instead of relying on:
setCount(count + 1);
Especially multiple updates में functional form useful है।
13. State with Objects
const [user, setUser] = useState({
name: "Raj",
age: 20
});
Update:
setUser(prev => ({
...prev,
age: 21
}));
Don’t:
user.age = 21;
14. State with Arrays
Add:
setUsers(prev => [
...prev,
newUser
]);
Remove:
setUsers(prev =>
prev.filter(user => user.id !== id)
);
Update:
setUsers(prev =>
prev.map(user =>
user.id === id
? { ...user, name: "New Name" }
: user
)
);
15. Conditional Rendering
Ternary
{isLoggedIn ? <Dashboard /> : <Login />}
AND
{isAdmin && <AdminPanel />}
Multiple conditions
{
status === "loading"
? <Loading />
: status === "error"
? <Error />
: <Content />
}
Better for complex UI:
if (status === "loading") {
return <Loading />;
}
if (status === "error") {
return <Error />;
}
return <Content />;
16. Rendering Lists
const users = [
{ id: 1, name: "Raj" },
{ id: 2, name: "Amit" }
];
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
Key क्यों जरूरी है?
React को list items identify करने में help करता है।
Good:
key={user.id}
Avoid:
key={index}
जब list reorder/delete/update हो सकती है।
17. Forms
Controlled input:
function Form() {
const [name, setName] = useState("");
return (
<input
value={name}
onChange={e => setName(e.target.value)}
/>
);
}
Form submit:
function Login() {
const handleSubmit = (e) => {
e.preventDefault();
console.log("Submit");
};
return (
<form onSubmit={handleSubmit}>
<input />
<button type="submit">
Login
</button>
</form>
);
}
18. Multiple Form Fields
const [form, setForm] = useState({
email: "",
password: ""
});
<input
name="email"
value={form.email}
onChange={handleChange}
/>
Handler:
const handleChange = (e) => {
const { name, value } = e.target;
setForm(prev => ({
...prev,
[name]: value
}));
};
19. useEffect
useEffect का use external systems के साथ synchronize करने के लिए होता है—जैसे network, browser APIs, subscriptions या non-React systems. हर derived value के लिए useEffect जरूरी नहीं है.
Basic:
useEffect(() => {
console.log("Effect");
});
Runs after relevant renders:
useEffect(() => {
console.log("Effect");
}, []);
Runs when dependency changes:
useEffect(() => {
console.log("User changed");
}, [userId]);
Cleanup:
useEffect(() => {
const timer = setInterval(() => {
console.log("Running");
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
20. Common useEffect Mistake
Don’t use Effect unnecessarily:
const fullName = firstName + " " + lastName;
Don’t do:
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);
Better:
const fullName = `${firstName} ${lastName}`;
Rule:
अगर value render के दौरान calculate हो सकती है, तो अक्सर उसे state + effect बनाने की जरूरत नहीं होती।
21. API Calls
Using fetch:
useEffect(() => {
async function fetchUsers() {
const response = await fetch(
"https://api.example.com/users"
);
const data = await response.json();
setUsers(data);
}
fetchUsers();
}, []);
Better production pattern:
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function loadData() {
try {
setLoading(true);
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch");
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}
loadData();
}, []);
UI:
if (loading) return <Loading />;
if (error) return <Error />;
return <UserList users={data} />;
22. useRef
useRef ऐसी information रखने के लिए useful है जिसे बदलने पर component को re-render नहीं करना चाहिए. DOM node access इसका common use case है.
DOM:
const inputRef = useRef(null);
<input ref={inputRef} />
Focus:
inputRef.current.focus();
Store mutable value:
const timerRef = useRef(null);
Important:
useState → change causes render
useRef → change does not cause render
23. useContext
Prop drilling avoid करने के लिए Context useful है।
Create:
const ThemeContext = createContext(null);
Provider:
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
Read:
const theme = useContext(ThemeContext);
Modern React में Context का use shared information जैसे theme/auth/preferences के लिए किया जा सकता है.
24. Context Pattern
const AuthContext = createContext(null);
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = (userData) => {
setUser(userData);
};
const logout = () => {
setUser(null);
};
return (
<AuthContext.Provider
value={{ user, login, logout }}
>
{children}
</AuthContext.Provider>
);
}
Custom hook:
function useAuth() {
return useContext(AuthContext);
}
Usage:
const { user, logout } = useAuth();
25. useReducer
Complex state logic के लिए:
const [state, dispatch] = useReducer(
reducer,
initialState
);
Reducer:
function reducer(state, action) {
switch (action.type) {
case "increment":
return {
...state,
count: state.count + 1
};
case "decrement":
return {
...state,
count: state.count - 1
};
default:
return state;
}
}
Dispatch:
dispatch({ type: "increment" });
With payload:
dispatch({
type: "addUser",
payload: user
});
26. useMemo
Expensive calculation का result cache करने के लिए:
const filteredUsers = useMemo(() => {
return users.filter(user =>
user.name.includes(search)
);
}, [users, search]);
लेकिन हर calculation को useMemo करने की जरूरत नहीं।
React Compiler modern React projects में automatic memoization कर सकता है, इसलिए manual optimization को blindly apply नहीं करना चाहिए.
27. useCallback
Function identity को cache करने के लिए:
const handleDelete = useCallback((id) => {
deleteUser(id);
}, [deleteUser]);
Useful especially when passing callbacks to memoized child components.
Don’t use everywhere.
28. React.memo
Component को unnecessary re-render से बचाने के लिए:
const UserCard = memo(function UserCard({
user
}) {
return <h2>{user.name}</h2>;
});
But:
memo ≠ automatically faster
पहले performance problem identify करो, फिर optimize करो।
29. useTransition
Non-blocking UI updates के लिए:
const [isPending, startTransition] =
useTransition();
function handleSearch(value) {
startTransition(() => {
setSearch(value);
});
}
UI:
{isPending && <p>Updating...</p>}
React के performance hooks में useTransition और useDeferredValue non-blocking/deferred updates के लिए available हैं.
30. useDeferredValue
const deferredSearch = useDeferredValue(search);
Use when:
User typing
↓
Input should stay responsive
↓
Heavy UI can update later
31. Custom Hooks
Reusable logic को custom Hook में निकाल सकते हैं।
Naming:
useSomething
Example:
function useWindowWidth() {
const [width, setWidth] = useState(
window.innerWidth
);
useEffect(() => {
const handleResize = () => {
setWidth(window.innerWidth);
};
window.addEventListener(
"resize",
handleResize
);
return () => {
window.removeEventListener(
"resize",
handleResize
);
};
}, []);
return width;
}
Usage:
const width = useWindowWidth();
32. Rules of Hooks
Rule 1
Hooks को top level पर call करो।
Correct:
function App() {
const [count, setCount] = useState(0);
return <div>{count}</div>;
}
Wrong:
if (isLoggedIn) {
const [user, setUser] = useState(null);
}
Rule 2
Hook को loop के अंदर नहीं:
for (...) {
useState();
}
Rule 3
Nested function में नहीं:
function handleClick() {
useState();
}
Rule 4
Regular JavaScript function से Hook call नहीं करना चाहिए।
Hooks केवल React functions या custom Hooks के appropriate top-level context में call करें.
33. React 19 – Important Modern Features
React 19 introduced several important APIs and improvements.
use#
import { use } from "react";
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return comments.map(comment => (
<p key={comment.id}>
{comment.text}
</p>
));
}
use Suspense-compatible resources जैसे Promise को render में read कर सकता है.
ref as a prop#
Modern React में function component में:
function MyInput({ ref }) {
return <input ref={ref} />;
}
React 19 ने function components के लिए ref को prop के रूप में access करने की सुविधा दी.
Actions / form-related APIs#
React 19 में async actions और form workflows के लिए:
useActionState()
जैसे APIs available हैं.
const [
state,
formAction,
isPending
] = useActionState(
action,
initialState
);
Suspense#
<Suspense fallback={<Loading />}>
<Profile />
</Suspense>
React के built-in components में Suspense, StrictMode, Fragment, Profiler और newer APIs शामिल हैं.
34. React 19.3 – What’s New
React 19.3 was released on September 9, 2026.
Important newer areas include:
View Transitions
Fragment Refs
browser()
Trusted Types
React Compiler improvements
For the latest changes, always check the official React blog/release notes rather than relying on old tutorials.
35. Rendering
Basic client rendering:
import {
createRoot
} from "react-dom/client";
createRoot(
document.getElementById("root")
).render(
<App />
);
React DOM provides browser-specific client APIs such as createRoot, as well as server/static rendering APIs.
36. StrictMode
<StrictMode>
<App />
</StrictMode>
Strict Mode development में bugs identify करने में मदद करता है.
Use it during development.
37. React Router
Install:
npm install react-router-dom
Basic:
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
<BrowserRouter>
<Routes>
<Route
path="/"
element={<Home />}
/>
<Route
path="/about"
element={<About />}
/>
<Route
path="/products"
element={<Products />}
/>
</Routes>
</BrowserRouter>
Navigate:
import { Link } from "react-router-dom";
<Link to="/about">
About
</Link>
Programmatic:
const navigate = useNavigate();
navigate("/dashboard");
38. Route Parameters
Route:
<Route
path="/users/:id"
element={<User />}
/>
Read:
const { id } = useParams();
Example:
/users/101
Result:
id === "101"
39. Protected Routes
Basic concept:
function ProtectedRoute({ children }) {
const { user } = useAuth();
if (!user) {
return <Navigate to="/login" />;
}
return children;
}
Usage:
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
40. API Layer
Instead of writing API calls everywhere:
components/
↓
hooks/
↓
services/
↓
API
Example:
// services/userService.js
export async function getUsers() {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed");
}
return response.json();
}
Component:
const users = await getUsers();
This makes applications easier to maintain.
41. Axios
Install:
npm install axios
Basic:
import axios from "axios";
const response = await axios.get(
"/api/users"
);
console.log(response.data);
POST:
await axios.post(
"/api/users",
{
name: "Raj",
email: "raj@example.com"
}
);
42. Environment Variables
Vite:
VITE_API_URL=https://api.example.com
Access:
const API_URL =
import.meta.env.VITE_API_URL;
Important:
Frontend environment variables are not secrets.
Never put:
Database password
Private API key
Secret token
in client-side environment variables.
43. Loading / Error / Empty States
Professional UI should handle:
Loading
Success
Error
Empty
Example:
if (loading) {
return <Loader />;
}
if (error) {
return <ErrorMessage />;
}
if (!users.length) {
return <EmptyState />;
}
return <UserList users={users} />;
This is one of the most important production React patterns.
44. Error Boundary
Error Boundary UI को unexpected rendering errors से recover/fallback करने में मदद करता है.
Concept:
<ErrorBoundary fallback={<ErrorPage />}>
<App />
</ErrorBoundary>
Important:
Error Boundary और
try/catchsame चीज नहीं हैं।
try/catch JavaScript errors handle करता है.
Error Boundary React rendering-related errors के लिए है.
45. Suspense
<Suspense fallback={<Loading />}>
<Profile />
</Suspense>
Concept:
Component loading
↓
Suspense boundary
↓
Fallback UI
↓
Component ready
↓
Real UI
46. Lazy Loading
const Dashboard = lazy(
() => import("./Dashboard")
);
Use:
<Suspense fallback={<Loading />}>
<Dashboard />
</Suspense>
Benefits:
Smaller initial bundle
↓
Faster initial load
↓
Load feature when required
47. State Management – कब क्या use करें?
Local UI state
↓
useState
Complex local state
↓
useReducer
Shared simple state
↓
Context
Large global application state
↓
State management library
Server/API state
↓
Dedicated server-state/data-fetching solution
Golden rule:
हर state को global मत बनाओ।
48. State Lifting
अगर दो sibling components को same data चाहिए:
Parent
/ \
Child A Child B
State parent में रखो:
function Parent() {
const [value, setValue] = useState("");
return (
<>
<ChildA
value={value}
setValue={setValue}
/>
<ChildB value={value} />
</>
);
}
49. Derived State
Avoid unnecessary state:
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
Don’t store:
const [fullName, setFullName] = useState("");
Instead:
const fullName =
`${firstName} ${lastName}`;
50. Immutability
Wrong:
user.name = "Raj";
Correct:
setUser(prev => ({
...prev,
name: "Raj"
}));
Array:
Wrong:
users.push(user);
Correct:
setUsers(prev => [
...prev,
user
]);
React’s rules emphasize immutable props and state because mutation can make rendering unpredictable and interfere with React’s optimization model.
51. Component Design
Bad:
App.jsx
└── 2000 lines
Better:
App
├── Navbar
├── Sidebar
├── Dashboard
│ ├── StatsCard
│ ├── Chart
│ └── RecentUsers
└── Footer
Component should generally have one clear responsibility.
Examples:
Button
Modal
Input
ProductCard
UserCard
Navbar
Sidebar
Pagination
Table
52. Smart vs Presentational Components
Older terminology:
Smart Component
↓
logic/data
Presentational Component
↓
UI
Modern practical approach:
Page / Feature
↓
Data + orchestration
↓
Reusable UI components
Don’t over-engineer every component.
53. Folder Architecture
Feature-based architecture:
src/
├── app/
│ ├── routes.jsx
│ └── providers.jsx
│
├── features/
│ ├── auth/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ └── pages/
│ │
│ └── products/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ └── pages/
│
├── components/
├── hooks/
├── services/
├── utils/
└── main.jsx
54. Common React Performance Problems
Problem 1: Huge component
Solution:
Split components
Problem 2: Unnecessary API requests
Solution:
Correct dependencies
Caching
Request management
Problem 3: Huge lists
Solution:
Pagination
Virtualization
Lazy loading
Problem 4: Expensive calculation
Solution:
Profile first
Then optimize
Problem 5: Unnecessary re-renders
Check:
State placement
Props
Context
Component structure
Memoization
55. React Performance Checklist
□ Keep state local when possible
□ Avoid unnecessary effects
□ Avoid unnecessary global state
□ Use stable keys
□ Lazy load large routes/features
□ Optimize large lists
□ Avoid expensive work during render
□ Profile before optimizing
□ Use memoization when it solves a real problem
□ Keep components focused
56. React DevTools
Use React DevTools to inspect:
Components
Props
State
Context
Render behavior
Performance
Useful for debugging component trees and performance.
57. Common Mistakes
Mistake 1: Mutating state#
Wrong:
user.name = "Raj";
Correct:
setUser({
...user,
name: "Raj"
});
Mistake 2: Missing key#
Wrong:
users.map(user => (
<UserCard user={user} />
))
Correct:
users.map(user => (
<UserCard
key={user.id}
user={user}
/>
))
Mistake 3: Using index as key#
key={index}
Can cause bugs when list order changes.
Prefer stable IDs.
Mistake 4: Wrong useEffect dependency#
useEffect(() => {
fetchUser(userId);
}, []);
If effect depends on userId, it should generally be included:
useEffect(() => {
fetchUser(userId);
}, [userId]);
Mistake 5: Calling function immediately#
Wrong:
<button onClick={handleClick()}>
Correct:
<button onClick={handleClick}>
With argument:
<button
onClick={() => handleClick(id)}
>
Mistake 6: Too much state#
Don’t store values that can be calculated.
Mistake 7: Too many useEffects#
Effect is not a replacement for normal JavaScript logic.
Mistake 8: Giant Context#
Don’t put every application state into one Context.
Mistake 9: Overusing memoization#
Don’t add:
useMemo()
useCallback()
memo()
everywhere without a measured reason.
Mistake 10: Ignoring loading/error states#
Production UI must handle failure.
58. React Interview Quick Questions
Q1. React क्या है?
JavaScript library for building user interfaces.
Q2. Component क्या है?
Reusable UI unit.
Q3. Props क्या हैं?
Parent से child को data देने का mechanism.
Q4. State क्या है?
Component की changing information.
Q5. Props और state में difference?
Props
→ parent controlled
→ read-only
State
→ component-controlled
→ can change
Q6. useState क्या करता है?
Component में state add करता है.
Q7. useEffect क्यों?
External systems के साथ synchronization के लिए.
Q8. useRef क्यों?
DOM/reference या non-rendering mutable value के लिए.
Q9. Context क्यों?
Deep component tree में shared data access के लिए.
Q10. Key क्यों?
List items को identify करने के लिए.
Q11. Controlled component?
Input value React state से controlled हो।
Q12. Uncontrolled component?
Input value DOM में managed हो; refs commonly used.
Q13. State lifting?
Shared state को common parent में move करना.
Q14. Prop drilling?
Data को कई component levels से manually pass करना.
Q15. Custom Hook?
Reusable stateful React logic.
59. React vs React Native
React
↓
Web
↓
HTML + CSS + Browser DOM
React Native
↓
Mobile
↓
iOS + Android
React concepts दोनों में काफी similar हैं:
Components
Props
State
Hooks
Context
Custom Hooks
लेकिन rendering layer अलग है।
60. React + TypeScript
Component:
type UserProps = {
name: string;
age: number;
};
function User({ name, age }: UserProps) {
return (
<div>
{name} - {age}
</div>
);
}
State:
const [users, setUsers] =
useState<User[]>([]);
Event:
const handleChange = (
e: React.ChangeEvent<HTMLInputElement>
) => {
console.log(e.target.value);
};
API type:
type User = {
id: number;
name: string;
email: string;
};
TypeScript + React large projects में bugs reduce करने और code maintain करने में useful है।
61. React + API Architecture
Recommended mental model:
UI
↓
Component
↓
Custom Hook
↓
Service/API Layer
↓
Backend
↓
Database
Example:
ProductPage
↓
useProducts()
↓
productService.getProducts()
↓
GET /api/products
↓
Backend
62. Authentication Flow
Basic:
Login Form
↓
POST /login
↓
Backend
↓
Token / Session
↓
Frontend Auth State
↓
Protected Routes
Typical pieces:
AuthProvider
useAuth()
ProtectedRoute
LoginPage
Logout
Refresh/session handling
Security principle:
Frontend route protection UX है; actual authorization backend पर enforce होना चाहिए।
63. CRUD Cheat Sheet
CRUD:
C → Create
R → Read
U → Update
D → Delete
HTTP:
POST → Create
GET → Read
PUT → Replace
PATCH → Partial update
DELETE → Delete
Example:
GET /api/products
POST /api/products
GET /api/products/10
PATCH /api/products/10
DELETE /api/products/10
64. Search + Filter
const filteredProducts = products.filter(
product =>
product.name
.toLowerCase()
.includes(search.toLowerCase())
);
Category:
const filtered = products.filter(
product =>
category === "all" ||
product.category === category
);
Combined:
const filtered = products.filter(product => {
const matchesSearch =
product.name
.toLowerCase()
.includes(search.toLowerCase());
const matchesCategory =
category === "all" ||
product.category === category;
return matchesSearch && matchesCategory;
});
65. Pagination
Basic concept:
const start =
(page - 1) * pageSize;
const end =
start + pageSize;
const visibleItems =
items.slice(start, end);
Production API:
GET /products?page=2&limit=20
Better for large datasets because the backend doesn’t need to send everything.
66. Debouncing Search
Problem:
User types:
R
Re
Rea
Reac
React
Without debounce:
5 API requests
With debounce:
React
↓
wait
↓
1 API request
Example concept:
useEffect(() => {
const timer = setTimeout(() => {
searchProducts(search);
}, 500);
return () => clearTimeout(timer);
}, [search]);
67. Local Storage
Save:
localStorage.setItem(
"theme",
"dark"
);
Read:
const theme =
localStorage.getItem("theme");
Remove:
localStorage.removeItem("theme");
JSON:
localStorage.setItem(
"user",
JSON.stringify(user)
);
Read:
const user = JSON.parse(
localStorage.getItem("user")
);
Always consider that browser storage is client-controlled and should not be treated as a secure secret store.
68. Accessibility
Use semantic HTML:
<button>
instead of:
<div onClick={...}>
Image:
<img
src="/logo.png"
alt="Company logo"
/>
Form:
<label htmlFor="email">
Email
</label>
<input id="email" />
Keyboard accessibility matters.
69. Security Checklist
□ Don't trust frontend validation
□ Validate on backend
□ Don't expose secrets
□ Sanitize untrusted HTML
□ Avoid unnecessary dangerouslySetInnerHTML
□ Use HTTPS
□ Handle authentication securely
□ Enforce authorization server-side
□ Keep dependencies updated
dangerouslySetInnerHTML should be used with extreme caution because untrusted HTML can introduce XSS vulnerabilities.
70. Testing
Common categories:
Unit Tests
Integration Tests
End-to-End Tests
Test:
Component rendering
User interaction
Forms
API behavior
Navigation
Critical business logic
Good test:
User clicks Login
↓
Form submits
↓
API succeeds
↓
Dashboard appears
Don’t test implementation details unnecessarily.
71. Production Checklist
□ Environment variables
□ Error handling
□ Loading states
□ Empty states
□ Responsive UI
□ Accessibility
□ Authentication
□ Authorization
□ API error handling
□ Validation
□ Performance
□ SEO where applicable
□ Analytics
□ Logging
□ Error monitoring
□ Tests
□ Production build
72. React Mental Model
सबसे important mental model:
Props
+
State
+
Context
↓
Render
↓
UI
User interaction:
User action
↓
Event handler
↓
State update
↓
React render
↓
Updated UI
External system:
React component
↓
Effect
↓
External system
73. React Golden Rules
1. Components को pure रखने की कोशिश करो.
2. State को directly mutate मत करो.
3. Hooks को top level पर call करो.
4. List में stable keys use करो.
5. हर चीज को state मत बनाओ.
6. हर चीज के लिए useEffect मत लगाओ.
7. State को जरूरत के सबसे नजदीक रखो.
8. Reusable logic को custom Hook में निकालो.
9. पहले profile करो, फिर performance optimize करो.
10. Backend authorization पर भरोसा रखो, frontend पर नहीं.
11. Small reusable components बनाओ.
12. Loading + error + empty states हमेशा सोचो.
13. Business logic और UI को जरूरत के अनुसार separate रखो.
14. Official React docs से current APIs सीखो.
15. Code पढ़ने लायक होना चाहिए, सिर्फ चलने लायक नहीं।
React की official Rules of React purity, immutable props/state और Rules of Hooks को core principles मानती हैं.
74. Quick Cheatsheet – Copy/Paste Ready
// ========== COMPONENT ==========
function User() {
return <h1>Hello</h1>;
}
// ========== PROPS ==========
function User({ name, age }) {
return (
<h2>
{name} - {age}
</h2>
);
}
<User name="Raj" age={20} />
// ========== STATE ==========
const [count, setCount] = useState(0);
setCount(10);
setCount(prev => prev + 1);
// ========== OBJECT STATE ==========
const [user, setUser] = useState({
name: "",
age: 20
});
setUser(prev => ({
...prev,
name: "Raj"
}));
// ========== ARRAY STATE ==========
setItems(prev => [
...prev,
newItem
]);
setItems(prev =>
prev.filter(item => item.id !== id)
);
setItems(prev =>
prev.map(item =>
item.id === id
? { ...item, name: "Updated" }
: item
)
);
// ========== EVENT ==========
<button onClick={handleClick}>
Click
</button>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
// ========== CONDITIONAL ==========
{isLoggedIn
? <Dashboard />
: <Login />
}
{isAdmin && <AdminPanel />}
// ========== LIST ==========
{users.map(user => (
<UserCard
key={user.id}
user={user}
/>
))}
// ========== EFFECT ==========
useEffect(() => {
// side effect
return () => {
// cleanup
};
}, [dependency]);
// ========== REF ==========
const inputRef = useRef(null);
<input ref={inputRef} />;
inputRef.current?.focus();
// ========== MEMO ==========
const result = useMemo(
() => expensiveCalculation(data),[data]
); // ========== CALLBACK ========== const handleClick = useCallback(() => { console.log(“clicked”); }, []); // ========== CONTEXT ========== const ThemeContext = createContext(null); const theme = useContext(ThemeContext); // ========== REDUCER ========== const [state, dispatch] = useReducer(reducer, initialState); dispatch({ type: “increment” }); // ========== CUSTOM HOOK ========== function useUsers() { const [users, setUsers] = useState([]); // reusable logic return users; } // ========== API ========== const response = await fetch(“/api/users”); const data = await response.json(); // ========== ROUTING ========== <Route path=”/users/:id” element={<User />} /> const { id } = useParams(); // ========== NAVIGATION ========== const navigate = useNavigate(); navigate(“/dashboard”); // ========== LAZY ========== const Dashboard = lazy( () => import(“./Dashboard”) ); <Suspense fallback={<Loading />}> <Dashboard /> </Suspense>;
75. React Hooks Quick Table
| Hook | Main Use |
|---|---|
useState | Local state |
useEffect | External synchronization |
useContext | Read context |
useRef | DOM / mutable value |
useReducer | Complex state logic |
useMemo | Cache calculation |
useCallback | Cache function |
useTransition | Non-blocking updates |
useDeferredValue | Defer non-critical value |
useId | Stable IDs/accessibility |
useSyncExternalStore | External stores |
useDebugValue | Custom Hook DevTools label |
useActionState | Action/form state |
use | Read resources/context in render |
React’s current reference lists these built-in Hooks and groups them by state, context, refs, effects, performance, and other use cases.
76. What Should You Learn First?
Beginner
□ JavaScript ES6+
□ JSX
□ Components
□ Props
□ Events
□ useState
□ Conditional rendering
□ Lists
□ Forms
Intermediate
□ useEffect
□ useRef
□ Context
□ useReducer
□ Custom Hooks
□ React Router
□ API integration
□ Authentication
□ CRUD
□ Error handling
Advanced
□ Suspense
□ useTransition
□ useDeferredValue
□ React Compiler
□ Performance profiling
□ Advanced architecture
□ Server rendering concepts
□ Testing
□ Accessibility
□ Production deployment
77. Practice Projects
Project 1 – Counter#
Learn:
useState
Events
Conditional rendering
Project 2 – Todo App#
Learn:
State
Forms
Arrays
CRUD
Components
Project 3 – Weather App#
Learn:
API
useEffect
Loading
Error
Search
Project 4 – Product Listing#
Learn:
API
Search
Filter
Sort
Pagination
Reusable components
Project 5 – Authentication App#
Learn:
Login
Register
Auth state
Protected routes
Logout
API
Project 6 – Admin Dashboard#
Learn:
Routing
Charts
CRUD
Tables
Forms
Authentication
Permissions
Project 7 – News Application#
Learn:
API
Categories
Search
Pagination
Bookmarks
Authentication
Notifications
Responsive UI
78. AI Prompts for React Practice
Copy-paste into ChatGPT/Claude:
Beginner
Teach me React useState like a beginner.
Explain it in simple Hinglish.
Give me one practical example,
then give me 5 exercises without solutions.
Debugging
Act as a senior React developer.
Here is my React code:
[PASTE CODE]
Find the bugs.
Explain why each bug happens.
Give the corrected code.
Also explain how I can avoid this mistake.
Interview
Act as a React interviewer.
Ask me one React interview question at a time.
Start from beginner level and gradually move
to advanced level.
Do not show the answer until I respond.
After my answer, rate it from 1-10.
Project
Help me build a production-quality React
e-commerce application.
Do not give me the entire code at once.
Break the project into milestones:
1. Architecture
2. Components
3. Routing
4. State
5. API
6. Authentication
7. Cart
8. Checkout
9. Testing
10. Deployment
Teach me while building.
Code Review
Review this React component like a senior
software engineer.
Check:
- readability
- component design
- state management
- useEffect usage
- performance
- accessibility
- security
- unnecessary complexity
Give specific improvements.
79. React Interview Revision Sheet
Before an interview, revise:
□ JSX
□ Components
□ Props
□ State
□ Events
□ Controlled components
□ Lists and keys
□ useEffect
□ useRef
□ useContext
□ useReducer
□ Custom Hooks
□ React Router
□ API integration
□ Authentication
□ State management
□ Performance
□ memo/useMemo/useCallback
□ Suspense
□ React 19 features
□ React Compiler
□ Testing
Must-answer questions
1. React क्या है?
2. React और JavaScript में difference?
3. Props vs State?
4. State mutation क्यों गलत है?
5. Virtual DOM क्या है?
6. Re-render क्या है?
7. useEffect कब use करना चाहिए?
8. useEffect कब नहीं use करना चाहिए?
9. useRef vs useState?
10. useMemo vs useCallback?
11. Context क्या solve करता है?
12. Prop drilling क्या है?
13. State lifting क्या है?
14. Custom Hook क्या है?
15. Key क्यों जरूरी है?
16. Controlled vs uncontrolled component?
17. React.memo क्या करता है?
18. Suspense क्या है?
19. useTransition क्या है?
20. React Compiler क्या करता है?
80. FAQ – 10 Common Questions
1. React framework है या library?#
React मुख्य रूप से UI library है। Routing, data fetching और other application concerns के लिए ecosystem/framework tools इस्तेमाल किए जा सकते हैं।
2. क्या React सीखने से पहले JavaScript आनी चाहिए?#
हाँ। कम से कम:
let/const
functions
arrow functions
objects
arrays
map/filter/reduce
destructuring
spread
modules
promises
async/await
closures
आना चाहिए।
3. क्या JSX HTML है?#
नहीं। JSX JavaScript syntax extension है जो UI structure लिखने को आसान बनाता है।
4. क्या हर component में state होना चाहिए?#
नहीं।
5. क्या हर component में useEffect होना चाहिए?#
नहीं। Effects external systems के साथ synchronization के लिए हैं.
6. useState और useRef में difference?#
useState
→ update → re-render
useRef
→ update → no re-render
7. Context क्या Redux का replacement है?#
Context और global state management tools अलग problems solve कर सकते हैं। Context primarily values को tree में उपलब्ध कराने का mechanism है।
8. React.memo कब use करें?#
जब profiling से पता चले कि unnecessary renders performance को प्रभावित कर रहे हैं।
9. क्या Class Components सीखने जरूरी हैं?#
Modern React development में function components और Hooks को प्राथमिकता दें। Class components अभी supported हैं, लेकिन नए code के लिए React function components recommend करता है.
10. React सीखने के बाद क्या सीखें?#
Recommended path:
React
↓
TypeScript
↓
React Router
↓
API / Backend
↓
Authentication
↓
Testing
↓
Next.js / Full-stack React
↓
Production Architecture
81. Official Resources
- React Learn – React fundamentals और daily-use concepts
https://react.dev/learn - React Reference – Hooks, APIs, Components और modern React APIs
https://react.dev/reference/react - React Hooks Reference – सभी built-in Hooks
https://react.dev/reference/react/hooks - Rules of React – purity, immutability और Hooks rules
https://react.dev/reference/rules - React Blog – latest releases और official announcements
https://react.dev/blog - React Versions – current और previous React versions
https://react.dev/versions
82. Final React Cheat Sheet
REACT
│
├── JSX
│
├── COMPONENTS
│ ├── Function Components
│ ├── Props
│ └── children
│
├── RENDERING
│ ├── Conditional
│ ├── Lists
│ └── Keys
│
├── EVENTS
│ ├── onClick
│ ├── onChange
│ └── onSubmit
│
├── STATE
│ ├── useState
│ ├── useReducer
│ └── State Lifting
│
├── EFFECTS
│ └── useEffect
│
├── REFS
│ └── useRef
│
├── SHARED STATE
│ ├── Context
│ └── State Libraries
│
├── REUSABLE LOGIC
│ └── Custom Hooks
│
├── ROUTING
│ └── React Router
│
├── API
│ ├── fetch
│ ├── Axios
│ ├── Loading
│ ├── Error
│ └── Empty State
│
├── PERFORMANCE
│ ├── memo
│ ├── useMemo
│ ├── useCallback
│ ├── useTransition
│ └── useDeferredValue
│
├── MODERN REACT
│ ├── Suspense
│ ├── use
│ ├── Actions
│ ├── ref as prop
│ └── React Compiler
│
├── QUALITY
│ ├── Accessibility
│ ├── Testing
│ ├── Security
│ └── Error Handling
│
└── PRODUCTION
├── Architecture
├── Authentication
├── Performance
├── Deployment
└── Monitoring
83. Conclusion – अब आगे क्या?
React को सिर्फ पढ़ने से mastery नहीं आएगी।
सबसे effective loop:
Learn
↓
Code
↓
Break
↓
Debug
↓
Understand
↓
Build
↓
Repeat
The Easy Master React Path
JavaScript
↓
React Fundamentals
↓
Hooks
↓
API Integration
↓
Routing
↓
Authentication
↓
TypeScript
↓
Real Projects
↓
Testing
↓
Performance
↓
Next.js / Full-Stack
↓
Job-Ready React Developer
React याद मत करो — React से बनाना सीखो।
Learn → Build → Practice → Challenge → Project → Become Job Ready.
Quick Revision Formula
Props = Data in
State = Data that changes
Event = User action
Effect = External synchronization
Ref = Mutable value / DOM reference
Context = Shared data
Hook = Reusable React logic
Component = Reusable UI
बस इन concepts को deeply समझ लो और छोटे-छोटे projects में repeatedly use करो — React की foundation strong हो जाएगी।