Skip to content

React Complete Cheat Sheet 2026

Updated 15 Sep 2026 11 min scan

1. React क्या है?

React एक JavaScript library है जिसका use interactive user interfaces बनाने के लिए किया जाता है।

React application को छोटे-छोटे components में divide करता है।

Code
function Welcome() {
  return <h1>Hello React!</h1>;
}

React का basic idea:

Code
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 सीखने का सही क्रम

Code
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 के साथ:

Code
CONCEPT
   ↓
EXAMPLE
   ↓
PRACTICE
   ↓
CHALLENGE
   ↓
PROJECT

3. React Project Setup

Modern React project के लिए commonly used setup:

Code
npm create vite@latest my-react-app
cd my-react-app
npm install
npm run dev

React install:

Code
npm install react react-dom

Production build:

Code
npm run build

Preview:

Code
npm run preview

4. Basic React Structure

Typical project:

Code
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:

Code
src/
├── components/
├── features/
├── pages/
├── hooks/
├── services/
├── context/
├── utils/
├── assets/
├── routes/
└── App.jsx

5. JSX

JSX का मतलब JavaScript XML है।

Code
const element = <h1>Hello World</h1>;

JavaScript expression:

Code
const name = "Raj";

return <h1>Hello {name}</h1>;

Expression:

Code
const age = 20;

return <p>Age: {age}</p>;

JavaScript:

Code
const user = {
  name: "Raj",
  age: 22
};

return (
  <div>
    <h2>{user.name}</h2>
    <p>{user.age}</p>
  </div>
);

JSX में class

HTML:

Code
<div class="box"></div>

React:

Code
<div className="box"></div>

JSX attributes

Code
<img src="/logo.png" alt="Logo" />
Code
<button disabled={true}>
  Submit
</button>

6. Components

React component एक JavaScript function होता है जो JSX return करता है.

Code
function Header() {
  return <header>My Website</header>;
}

Use:

Code
function App() {
  return (
    <>
      <Header />
      <main>Hello</main>
    </>
  );
}

Component naming

Good:

Code
function UserProfile() {}
function ProductCard() {}
function Navbar() {}

Avoid:

Code
function userprofile() {}

Component names generally PascalCase में रखें।


7. Fragment

Extra <div> create करने की जरूरत नहीं:

Code
<>
  <h1>Hello</h1>
  <p>Welcome</p>
</>

या:

Code
<React.Fragment>
  <h1>Hello</h1>
  <p>Welcome</p>
</React.Fragment>

8. Props

Props parent से child component को data भेजने के लिए use होते हैं।

Code
function User({ name }) {
  return <h2>Hello {name}</h2>;
}

function App() {
  return <User name="Raj" />;
}

Multiple props:

Code
function Product({ name, price, category }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>{category}</p>
      <strong>₹{price}</strong>
    </div>
  );
}

Use:

Code
<Product
  name="Laptop"
  price={50000}
  category="Electronics"
/>

Props are read-only

Don’t do:

Code
props.name = "New Name";

Props और state को directly mutate नहीं करना चाहिए. React इन्हें render के लिए immutable snapshots की तरह treat करता है.


9. children Prop

Code
function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}

Use:

Code
<Card>
  <h2>Hello</h2>
  <p>React is powerful.</p>
</Card>

10. Event Handling

HTML:

Code
<button onclick="handleClick()">

React:

Code
<button onClick={handleClick}>

Example:

Code
function App() {
  const handleClick = () => {
    console.log("Clicked");
  };

  return <button onClick={handleClick}>Click</button>;
}

Inline:

Code
<button onClick={() => console.log("Clicked")}>
  Click
</button>

Input:

Code
<input onChange={(e) => console.log(e.target.value)} />

Common events:

Code
onClick
onChange
onSubmit
onFocus
onBlur
onKeyDown
onKeyUp
onMouseEnter
onMouseLeave

11. State – useState

State component की changing information को store करता है।

Code
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <>
      <p>{count}</p>

      <button onClick={() => setCount(count + 1)}>
        +
      </button>
    </>
  );
}

Syntax:

Code
const [state, setState] = useState(initialValue);

Examples:

Code
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 करता है:

Code
setCount(prev => prev + 1);

Better:

Code
setCount(prev => prev + 1);

Instead of relying on:

Code
setCount(count + 1);

Especially multiple updates में functional form useful है।


13. State with Objects

Code
const [user, setUser] = useState({
  name: "Raj",
  age: 20
});

Update:

Code
setUser(prev => ({
  ...prev,
  age: 21
}));

Don’t:

Code
user.age = 21;

14. State with Arrays

Add:

Code
setUsers(prev => [
  ...prev,
  newUser
]);

Remove:

Code
setUsers(prev =>
  prev.filter(user => user.id !== id)
);

Update:

Code
setUsers(prev =>
  prev.map(user =>
    user.id === id
      ? { ...user, name: "New Name" }
      : user
  )
);

15. Conditional Rendering

Ternary

Code
{isLoggedIn ? <Dashboard /> : <Login />}

AND

Code
{isAdmin && <AdminPanel />}

Multiple conditions

Code
{
  status === "loading"
    ? <Loading />
    : status === "error"
      ? <Error />
      : <Content />
}

Better for complex UI:

Code
if (status === "loading") {
  return <Loading />;
}

if (status === "error") {
  return <Error />;
}

return <Content />;

16. Rendering Lists

Code
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:

Code
key={user.id}

Avoid:

Code
key={index}

जब list reorder/delete/update हो सकती है।


17. Forms

Controlled input:

Code
function Form() {
  const [name, setName] = useState("");

  return (
    <input
      value={name}
      onChange={e => setName(e.target.value)}
    />
  );
}

Form submit:

Code
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

Code
const [form, setForm] = useState({
  email: "",
  password: ""
});
Code
<input
  name="email"
  value={form.email}
  onChange={handleChange}
/>

Handler:

Code
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:

Code
useEffect(() => {
  console.log("Effect");
});

Runs after relevant renders:

Code
useEffect(() => {
  console.log("Effect");
}, []);

Runs when dependency changes:

Code
useEffect(() => {
  console.log("User changed");
}, [userId]);

Cleanup:

Code
useEffect(() => {
  const timer = setInterval(() => {
    console.log("Running");
  }, 1000);

  return () => {
    clearInterval(timer);
  };
}, []);

20. Common useEffect Mistake

Don’t use Effect unnecessarily:

Code
const fullName = firstName + " " + lastName;

Don’t do:

Code
const [fullName, setFullName] = useState("");

useEffect(() => {
  setFullName(firstName + " " + lastName);
}, [firstName, lastName]);

Better:

Code
const fullName = `${firstName} ${lastName}`;

Rule:

अगर value render के दौरान calculate हो सकती है, तो अक्सर उसे state + effect बनाने की जरूरत नहीं होती।


21. API Calls

Using fetch:

Code
useEffect(() => {
  async function fetchUsers() {
    const response = await fetch(
      "https://api.example.com/users"
    );

    const data = await response.json();

    setUsers(data);
  }

  fetchUsers();
}, []);

Better production pattern:

Code
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:

Code
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:

Code
const inputRef = useRef(null);

<input ref={inputRef} />

Focus:

Code
inputRef.current.focus();

Store mutable value:

Code
const timerRef = useRef(null);

Important:

Code
useState → change causes render
useRef   → change does not cause render

23. useContext

Prop drilling avoid करने के लिए Context useful है।

Create:

Code
const ThemeContext = createContext(null);

Provider:

Code
<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>

Read:

Code
const theme = useContext(ThemeContext);

Modern React में Context का use shared information जैसे theme/auth/preferences के लिए किया जा सकता है.


24. Context Pattern

Code
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:

Code
function useAuth() {
  return useContext(AuthContext);
}

Usage:

Code
const { user, logout } = useAuth();

25. useReducer

Complex state logic के लिए:

Code
const [state, dispatch] = useReducer(
  reducer,
  initialState
);

Reducer:

Code
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:

Code
dispatch({ type: "increment" });

With payload:

Code
dispatch({
  type: "addUser",
  payload: user
});

26. useMemo

Expensive calculation का result cache करने के लिए:

Code
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 करने के लिए:

Code
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 से बचाने के लिए:

Code
const UserCard = memo(function UserCard({
  user
}) {
  return <h2>{user.name}</h2>;
});

But:

Code
memo ≠ automatically faster

पहले performance problem identify करो, फिर optimize करो।


29. useTransition

Non-blocking UI updates के लिए:

Code
const [isPending, startTransition] =
  useTransition();

function handleSearch(value) {
  startTransition(() => {
    setSearch(value);
  });
}

UI:

Code
{isPending && <p>Updating...</p>}

React के performance hooks में useTransition और useDeferredValue non-blocking/deferred updates के लिए available हैं.


30. useDeferredValue

Code
const deferredSearch = useDeferredValue(search);

Use when:

Code
User typing
     ↓
Input should stay responsive
     ↓
Heavy UI can update later

31. Custom Hooks

Reusable logic को custom Hook में निकाल सकते हैं।

Naming:

Code
useSomething

Example:

Code
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:

Code
const width = useWindowWidth();

32. Rules of Hooks

Rule 1

Hooks को top level पर call करो।

Correct:

Code
function App() {
  const [count, setCount] = useState(0);

  return <div>{count}</div>;
}

Wrong:

Code
if (isLoggedIn) {
  const [user, setUser] = useState(null);
}

Rule 2

Hook को loop के अंदर नहीं:

Code
for (...) {
  useState();
}

Rule 3

Nested function में नहीं:

Code
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#

Code
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 में:

Code
function MyInput({ ref }) {
  return <input ref={ref} />;
}

React 19 ने function components के लिए ref को prop के रूप में access करने की सुविधा दी.

React 19 में async actions और form workflows के लिए:

Code
useActionState()

जैसे APIs available हैं.

Code
const [
  state,
  formAction,
  isPending
] = useActionState(
  action,
  initialState
);

Suspense#

Code
<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:

Code
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:

Code
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

Code
<StrictMode>
  <App />
</StrictMode>

Strict Mode development में bugs identify करने में मदद करता है.

Use it during development.


37. React Router

Install:

Code
npm install react-router-dom

Basic:

Code
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
Code
<BrowserRouter>
  <Routes>
    <Route
      path="/"
      element={<Home />}
    />

    <Route
      path="/about"
      element={<About />}
    />

    <Route
      path="/products"
      element={<Products />}
    />
  </Routes>
</BrowserRouter>

Navigate:

Code
import { Link } from "react-router-dom";

<Link to="/about">
  About
</Link>

Programmatic:

Code
const navigate = useNavigate();

navigate("/dashboard");

38. Route Parameters

Route:

Code
<Route
  path="/users/:id"
  element={<User />}
/>

Read:

Code
const { id } = useParams();

Example:

Code
/users/101

Result:

Code
id === "101"

39. Protected Routes

Basic concept:

Code
function ProtectedRoute({ children }) {
  const { user } = useAuth();

  if (!user) {
    return <Navigate to="/login" />;
  }

  return children;
}

Usage:

Code
<Route
  path="/dashboard"
  element={
    <ProtectedRoute>
      <Dashboard />
    </ProtectedRoute>
  }
/>

40. API Layer

Instead of writing API calls everywhere:

Code
components/
   ↓
hooks/
   ↓
services/
   ↓
API

Example:

Code
// services/userService.js

export async function getUsers() {
  const response = await fetch("/api/users");

  if (!response.ok) {
    throw new Error("Failed");
  }

  return response.json();
}

Component:

Code
const users = await getUsers();

This makes applications easier to maintain.


41. Axios

Install:

Code
npm install axios

Basic:

Code
import axios from "axios";

const response = await axios.get(
  "/api/users"
);

console.log(response.data);

POST:

Code
await axios.post(
  "/api/users",
  {
    name: "Raj",
    email: "raj@example.com"
  }
);

42. Environment Variables

Vite:

Code
VITE_API_URL=https://api.example.com

Access:

Code
const API_URL =
  import.meta.env.VITE_API_URL;

Important:

Frontend environment variables are not secrets.

Never put:

Code
Database password
Private API key
Secret token

in client-side environment variables.


43. Loading / Error / Empty States

Professional UI should handle:

Code
Loading
Success
Error
Empty

Example:

Code
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:

Code
<ErrorBoundary fallback={<ErrorPage />}>
  <App />
</ErrorBoundary>

Important:

Error Boundary और try/catch same चीज नहीं हैं।

try/catch JavaScript errors handle करता है.

Error Boundary React rendering-related errors के लिए है.


45. Suspense

Code
<Suspense fallback={<Loading />}>
  <Profile />
</Suspense>

Concept:

Code
Component loading
      ↓
Suspense boundary
      ↓
Fallback UI
      ↓
Component ready
      ↓
Real UI

46. Lazy Loading

Code
const Dashboard = lazy(
  () => import("./Dashboard")
);

Use:

Code
<Suspense fallback={<Loading />}>
  <Dashboard />
</Suspense>

Benefits:

Code
Smaller initial bundle
       ↓
Faster initial load
       ↓
Load feature when required

47. State Management – कब क्या use करें?

Code
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 चाहिए:

Code
        Parent
       /      \
   Child A   Child B

State parent में रखो:

Code
function Parent() {
  const [value, setValue] = useState("");

  return (
    <>
      <ChildA
        value={value}
        setValue={setValue}
      />

      <ChildB value={value} />
    </>
  );
}

49. Derived State

Avoid unnecessary state:

Code
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");

Don’t store:

Code
const [fullName, setFullName] = useState("");

Instead:

Code
const fullName =
  `${firstName} ${lastName}`;

50. Immutability

Wrong:

Code
user.name = "Raj";

Correct:

Code
setUser(prev => ({
  ...prev,
  name: "Raj"
}));

Array:

Wrong:

Code
users.push(user);

Correct:

Code
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:

Code
App.jsx
 └── 2000 lines

Better:

Code
App
├── Navbar
├── Sidebar
├── Dashboard
│   ├── StatsCard
│   ├── Chart
│   └── RecentUsers
└── Footer

Component should generally have one clear responsibility.

Examples:

Code
Button
Modal
Input
ProductCard
UserCard
Navbar
Sidebar
Pagination
Table

52. Smart vs Presentational Components

Older terminology:

Code
Smart Component
    ↓
logic/data

Presentational Component
    ↓
UI

Modern practical approach:

Code
Page / Feature
    ↓
Data + orchestration
    ↓
Reusable UI components

Don’t over-engineer every component.


53. Folder Architecture

Feature-based architecture:

Code
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:

Code
Split components

Problem 2: Unnecessary API requests

Solution:

Code
Correct dependencies
Caching
Request management

Problem 3: Huge lists

Solution:

Code
Pagination
Virtualization
Lazy loading

Problem 4: Expensive calculation

Solution:

Code
Profile first
Then optimize

Problem 5: Unnecessary re-renders

Check:

Code
State placement
Props
Context
Component structure
Memoization

55. React Performance Checklist

Code
□ 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:

Code
Components
Props
State
Context
Render behavior
Performance

Useful for debugging component trees and performance.


57. Common Mistakes

Mistake 1: Mutating state#

Wrong:

Code
user.name = "Raj";

Correct:

Code
setUser({
  ...user,
  name: "Raj"
});

Mistake 2: Missing key#

Wrong:

Code
users.map(user => (
  <UserCard user={user} />
))

Correct:

Code
users.map(user => (
  <UserCard
    key={user.id}
    user={user}
  />
))

Mistake 3: Using index as key#

Code
key={index}

Can cause bugs when list order changes.

Prefer stable IDs.


Mistake 4: Wrong useEffect dependency#

Code
useEffect(() => {
  fetchUser(userId);
}, []);

If effect depends on userId, it should generally be included:

Code
useEffect(() => {
  fetchUser(userId);
}, [userId]);

Mistake 5: Calling function immediately#

Wrong:

Code
<button onClick={handleClick()}>

Correct:

Code
<button onClick={handleClick}>

With argument:

Code
<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:

Code
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?

Code
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

Code
React
 ↓
Web
 ↓
HTML + CSS + Browser DOM
Code
React Native
 ↓
Mobile
 ↓
iOS + Android

React concepts दोनों में काफी similar हैं:

Code
Components
Props
State
Hooks
Context
Custom Hooks

लेकिन rendering layer अलग है।


60. React + TypeScript

Component:

Code
type UserProps = {
  name: string;
  age: number;
};

function User({ name, age }: UserProps) {
  return (
    <div>
      {name} - {age}
    </div>
  );
}

State:

Code
const [users, setUsers] =
  useState<User[]>([]);

Event:

Code
const handleChange = (
  e: React.ChangeEvent<HTMLInputElement>
) => {
  console.log(e.target.value);
};

API type:

Code
type User = {
  id: number;
  name: string;
  email: string;
};

TypeScript + React large projects में bugs reduce करने और code maintain करने में useful है।


61. React + API Architecture

Recommended mental model:

Code
UI
 ↓
Component
 ↓
Custom Hook
 ↓
Service/API Layer
 ↓
Backend
 ↓
Database

Example:

Code
ProductPage
    ↓
useProducts()
    ↓
productService.getProducts()
    ↓
GET /api/products
    ↓
Backend

62. Authentication Flow

Basic:

Code
Login Form
   ↓
POST /login
   ↓
Backend
   ↓
Token / Session
   ↓
Frontend Auth State
   ↓
Protected Routes

Typical pieces:

Code
AuthProvider
useAuth()
ProtectedRoute
LoginPage
Logout
Refresh/session handling

Security principle:

Frontend route protection UX है; actual authorization backend पर enforce होना चाहिए।


63. CRUD Cheat Sheet

CRUD:

Code
C → Create
R → Read
U → Update
D → Delete

HTTP:

Code
POST   → Create
GET    → Read
PUT    → Replace
PATCH  → Partial update
DELETE → Delete

Example:

Code
GET    /api/products
POST   /api/products
GET    /api/products/10
PATCH  /api/products/10
DELETE /api/products/10

64. Search + Filter

Code
const filteredProducts = products.filter(
  product =>
    product.name
      .toLowerCase()
      .includes(search.toLowerCase())
);

Category:

Code
const filtered = products.filter(
  product =>
    category === "all" ||
    product.category === category
);

Combined:

Code
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:

Code
const start =
  (page - 1) * pageSize;

const end =
  start + pageSize;

const visibleItems =
  items.slice(start, end);

Production API:

Code
GET /products?page=2&limit=20

Better for large datasets because the backend doesn’t need to send everything.


66. Debouncing Search

Problem:

Code
User types:
R
Re
Rea
Reac
React

Without debounce:

Code
5 API requests

With debounce:

Code
React
 ↓
wait
 ↓
1 API request

Example concept:

Code
useEffect(() => {
  const timer = setTimeout(() => {
    searchProducts(search);
  }, 500);

  return () => clearTimeout(timer);
}, [search]);

67. Local Storage

Save:

Code
localStorage.setItem(
  "theme",
  "dark"
);

Read:

Code
const theme =
  localStorage.getItem("theme");

Remove:

Code
localStorage.removeItem("theme");

JSON:

Code
localStorage.setItem(
  "user",
  JSON.stringify(user)
);

Read:

Code
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:

Code
<button>

instead of:

Code
<div onClick={...}>

Image:

Code
<img
  src="/logo.png"
  alt="Company logo"
/>

Form:

Code
<label htmlFor="email">
  Email
</label>

<input id="email" />

Keyboard accessibility matters.


69. Security Checklist

Code
□ 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:

Code
Unit Tests
Integration Tests
End-to-End Tests

Test:

Code
Component rendering
User interaction
Forms
API behavior
Navigation
Critical business logic

Good test:

Code
User clicks Login
      ↓
Form submits
      ↓
API succeeds
      ↓
Dashboard appears

Don’t test implementation details unnecessarily.


71. Production Checklist

Code
□ 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:

Code
Props
  +
State
  +
Context
  ↓
Render
  ↓
UI

User interaction:

Code
User action
   ↓
Event handler
   ↓
State update
   ↓
React render
   ↓
Updated UI

External system:

Code
React component
      ↓
Effect
      ↓
External system

73. React Golden Rules

Code
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

Code
// ========== 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

HookMain Use
useStateLocal state
useEffectExternal synchronization
useContextRead context
useRefDOM / mutable value
useReducerComplex state logic
useMemoCache calculation
useCallbackCache function
useTransitionNon-blocking updates
useDeferredValueDefer non-critical value
useIdStable IDs/accessibility
useSyncExternalStoreExternal stores
useDebugValueCustom Hook DevTools label
useActionStateAction/form state
useRead 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

Code
□ JavaScript ES6+
□ JSX
□ Components
□ Props
□ Events
□ useState
□ Conditional rendering
□ Lists
□ Forms

Intermediate

Code
□ useEffect
□ useRef
□ Context
□ useReducer
□ Custom Hooks
□ React Router
□ API integration
□ Authentication
□ CRUD
□ Error handling

Advanced

Code
□ Suspense
□ useTransition
□ useDeferredValue
□ React Compiler
□ Performance profiling
□ Advanced architecture
□ Server rendering concepts
□ Testing
□ Accessibility
□ Production deployment

77. Practice Projects

Project 1 – Counter#

Learn:

Code
useState
Events
Conditional rendering

Project 2 – Todo App#

Learn:

Code
State
Forms
Arrays
CRUD
Components

Project 3 – Weather App#

Learn:

Code
API
useEffect
Loading
Error
Search

Project 4 – Product Listing#

Learn:

Code
API
Search
Filter
Sort
Pagination
Reusable components

Project 5 – Authentication App#

Learn:

Code
Login
Register
Auth state
Protected routes
Logout
API

Project 6 – Admin Dashboard#

Learn:

Code
Routing
Charts
CRUD
Tables
Forms
Authentication
Permissions

Project 7 – News Application#

Learn:

Code
API
Categories
Search
Pagination
Bookmarks
Authentication
Notifications
Responsive UI

78. AI Prompts for React Practice

Copy-paste into ChatGPT/Claude:

Beginner

Code
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

Code
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

Code
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

Code
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

Code
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:

Code
□ 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

Code
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 आनी चाहिए?#

हाँ। कम से कम:

Code
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?#

Code
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:

Code
React
 ↓
TypeScript
 ↓
React Router
 ↓
API / Backend
 ↓
Authentication
 ↓
Testing
 ↓
Next.js / Full-stack React
 ↓
Production Architecture

81. Official Resources

  1. React Learn – React fundamentals और daily-use concepts
    https://react.dev/learn
  2. React Reference – Hooks, APIs, Components और modern React APIs
    https://react.dev/reference/react
  3. React Hooks Reference – सभी built-in Hooks
    https://react.dev/reference/react/hooks
  4. Rules of React – purity, immutability और Hooks rules
    https://react.dev/reference/rules
  5. React Blog – latest releases और official announcements
    https://react.dev/blog
  6. React Versions – current और previous React versions
    https://react.dev/versions

82. Final React Cheat Sheet

Code
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:

Code
Learn
  ↓
Code
  ↓
Break
  ↓
Debug
  ↓
Understand
  ↓
Build
  ↓
Repeat

The Easy Master React Path

Code
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

Code
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 हो जाएगी।