Skip to content

React Cheat Sheet – Complete Guide in Hindi

Updated 20 Oct 2026 9 min scan

React एक popular JavaScript library है, जिसका उपयोग interactive user interfaces (UI) बनाने के लिए किया जाता है। इसकी मदद से आप reusable components बनाकर websites और web applications का frontend develop कर सकते हैं।

अगर आप JavaScript सीख चुके हैं, तो React आपके लिए अगला important step है। React का उपयोग dashboards, e-commerce websites, admin panels, social media interfaces और single-page applications बनाने में किया जाता है।

इस React Cheat Sheet में हम basics से शुरू करके JSX, components, props, state, hooks, events, forms, API integration, React Router और performance optimization तक practical examples के साथ सीखेंगे।

1. React क्या है?#

React एक JavaScript library है, जिसे user interfaces बनाने के लिए इस्तेमाल किया जाता है। इसमें UI को छोटे-छोटे reusable components में divide किया जाता है।

Simple words में, React आपको पूरी website को एक बड़े code block में बनाने के बजाय छोटे और manageable parts में बनाने देता है।

उदाहरण के लिए, एक e-commerce website में ये components हो सकते हैं:

  • Header
  • Navigation
  • Search bar
  • Product card
  • Product list
  • Shopping cart
  • Footer

हर component की अपनी जिम्मेदारी होती है। एक बार Product Card component बना लेने के बाद आप उसे कई products के लिए reuse कर सकते हैं।

React क्यों use करते हैं?

  • Reusable UI components बनाने के लिए।
  • User interaction के अनुसार UI update करने के लिए।
  • बड़े frontend को manageable parts में divide करने के लिए।
  • Components के बीच data pass करने के लिए।
  • State और events को structured तरीके से handle करने के लिए।
  • JavaScript ecosystem के दूसरे tools और libraries के साथ काम करने के लिए।

React कैसे काम करता है?

React आपके components से UI का description लेता है और उसके आधार पर browser DOM में जरूरी updates करता है।

Code
User Interaction
       |
       v
State Update
       |
       v
Component Re-render
       |
       v
React Updates the DOM
       |
       v
Updated UI

उदाहरण के लिए, जब user Add to Cart button पर click करता है, तो cart की state update हो सकती है और cart count screen पर नया दिखाई दे सकता है।

2. React Setup कैसे करें?#

React project शुरू करने के लिए आप Vite का उपयोग कर सकते हैं। Vite development server और production build के लिए tooling उपलब्ध कराता है।

Step 1: Node.js और npm check करें

Terminal में चलाएँ:

Code
node -v
npm -v

अगर दोनों commands version दिखाती हैं, तो आप आगे बढ़ सकते हैं।

Step 2: React Project बनाएँ

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

Step 3: Development Server शुरू करें

Code
npm run dev

Terminal में Vite local development URL दिखाएगा। उसे browser में open करें।

React + TypeScript Project

अगर आप TypeScript के साथ React सीखना चाहते हैं:

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

इस template में TypeScript और React के लिए शुरुआती configuration मौजूद होती है।

Important Commands

Commandकाम
npm installDependencies install करना
npm run devDevelopment server शुरू करना
npm run buildProduction build बनाना
npm run previewProduction build को locally preview करना

ध्यान दें: npm run preview production deployment का replacement नहीं है। यह local preview के लिए होता है।

Reference: Vite Getting Started

3. React Project Structure#

एक basic Vite + React project की structure इस तरह हो सकती है:

Code
my-react-app/
├── public/
├── src/
│   ├── assets/
│   ├── components/
│   │   ├── Header.jsx
│   │   └── ProductCard.jsx
│   ├── App.jsx
│   ├── main.jsx
│   └── index.css
├── index.html
├── package.json
└── vite.config.js
File / FolderPurpose
src/React application का source code
components/Reusable UI components
App.jsxMain application component
main.jsxReact application का entry point
assets/Imported images और दूसरे assets
public/Static files जिन्हें public path से serve किया जाता है
index.cssGlobal styles
package.jsonDependencies और npm scripts
vite.config.jsVite configuration

यह एक example structure है। छोटे projects में सभी folders जरूरी नहीं हैं। Project बढ़ने पर components, pages, hooks, services और utilities के अलग folders बनाए जा सकते हैं।

4. JSX क्या है?#

JSX का full form JavaScript XML है। यह JavaScript के अंदर HTML जैसी syntax में UI describe करने देता है।

Example:

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

export default App;

यहाँ return के अंदर JSX लिखा गया है।

JSX browser द्वारा directly execute नहीं किया जाता। React project में Vite जैसे tools JSX को browser-compatible JavaScript में transform करते हैं।

JSX में JavaScript Expressions

Curly braces {} के अंदर JavaScript expressions लिख सकते हैं।

Code
function App() {
  const name = "Aman";
  const age = 25;

  return (
    <div>
      <h1>Hello, {name}</h1>
      <p>Your age is {age}</p>
      <p>Next year: {age + 1}</p>
    </div>
  );
}

export default App;

JSX में Important Rules

1. एक parent element return करें।

Code
function App() {
  return (
    <div>
      <h1>React</h1>
      <p>Learn components</p>
    </div>
  );
}

अगर extra DOM element नहीं चाहिए, तो Fragment use कर सकते हैं:

Code
function App() {
  return (
    <>
      <h1>React</h1>
      <p>Learn components</p>
    </>
  );
}

2. HTML के class की जगह className use करें।

Code
<div className="container">Hello</div>

3. कुछ HTML attributes camelCase में लिखे जाते हैं।

Code
<button onClick={handleClick}>Click</button>

4. JSX tags को properly close करें।

Code
<img src="/logo.png" alt="Logo" />
<input type="text" />

5. JavaScript statements और expressions में अंतर समझें।

JSX के अंदर सीधे if statement नहीं लिख सकते, लेकिन conditional expression use कर सकते हैं।

Code
const isLoggedIn = true;

return <p>{isLoggedIn ? "Welcome" : "Please log in"}</p>;

5. React Components#

Component UI का एक reusable हिस्सा होता है। Modern React में function components सबसे common approach हैं।

Basic Component

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

export default Header;

Component को Import और Use करना

Header.jsx:

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

export default Header;

App.jsx:

Code
import Header from "./Header";

function App() {
  return (
    <div>
      <Header />
      <main>Welcome to my website</main>
    </div>
  );
}

export default App;

Multiple Components

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

function MainContent() {
  return <main>Learn React step by step</main>;
}

function Footer() {
  return <footer>Copyright 2026</footer>;
}

function App() {
  return (
    <>
      <Header />
      <MainContent />
      <Footer />
    </>
  );
}

export default App;

Component Naming Rules

  • Component का नाम capital letter से शुरू करें।
  • Components reusable और focused रखें।
  • Related UI और logic को साथ रखें।
  • जब component बहुत बड़ा हो जाए, तो उसे छोटे components में divide करने पर विचार करें।

React components के नाम PascalCase में लिखना common convention है, जैसे ProductCard, UserProfile और Navbar।

6. Props क्या हैं?#

Props का उपयोग parent component से child component में data pass करने के लिए किया जाता है।

Simple words में, props component के inputs होते हैं।

Basic Props Example

Code
function Greeting(props) {
  return <h2>Hello, {props.name}</h2>;
}

function App() {
  return (
    <>
      <Greeting name="Aman" />
      <Greeting name="Riya" />
      <Greeting name="Rahul" />
    </>
  );
}

export default App;

तीनों instances में same component अलग-अलग data के साथ render होता है।

Props Destructuring

Code
function Greeting({ name, city }) {
  return (
    <p>
      Hello {name} from {city}
    </p>
  );
}

function App() {
  return <Greeting name="Aman" city="Chandigarh" />;
}

export default App;

Destructuring से component code readable बनता है।

Default Values

Code
function Greeting({ name = "Guest" }) {
  return <h2>Hello, {name}</h2>;
}

अगर name prop missing या undefined है, तो "Guest" use होगा।

Props Read-only होते हैं

Child component को props को directly modify नहीं करना चाहिए।

Code
function User({ name }) {
  // name = "Rahul"; // Props को इस तरह modify न करें

  return <h2>{name}</h2>;
}

अगर value बदलनी है, तो parent component state update कर सकता है या child को callback prop दे सकता है।

7. State और useState#

State वह data है जिसे component याद रखता है और जिसके बदलने पर UI update हो सकता है।

उदाहरण के लिए:

  • Counter value
  • Modal open या closed होना
  • Form input
  • Selected product
  • Cart items
  • Loading status

React में local component state manage करने के लिए useState hook use किया जाता है।

Basic Counter

Code
import { useState } from "react";

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

  return (
    <div>
      <h2>Count: {count}</h2>

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

      <button onClick={() => setCount(count - 1)}>
        Decrease
      </button>
    </div>
  );
}

export default Counter;

useState कैसे काम करता है?

Code
const [count, setCount] = useState(0);
  • count: Current state value।
  • setCount: State update करने वाला function।
  • 0: Initial state value।

जब setCount से state update होती है, React component को re-render कर सकता है और updated value UI में दिखाई देती है।

Previous State के आधार पर Update

अगर नई state previous state पर depend करती है, तो updater function use करना बेहतर है।

Code
setCount((previousCount) => previousCount + 1);

उदाहरण:

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

  function increaseTwice() {
    setCount((previous) => previous + 1);
    setCount((previous) => previous + 1);
  }

  return (
    <button onClick={increaseTwice}>
      Count: {count}
    </button>
  );
}

यहाँ एक click पर count दो से बढ़ता है।

State को Directly Modify न करें

गलत approach:

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

// गलत
user.age = 26;

सही approach:

Code
setUser((previousUser) => ({
  ...previousUser,
  age: 26
}));

React state में objects और arrays को immutable तरीके से update करना चाहिए, ताकि React सही changes पहचान सके।

Official reference: React useState

8. Event Handling#

Events user interactions को handle करते हैं, जैसे button click, input change और form submission।

Click Event

Code
function App() {
  function handleClick() {
    alert("Button clicked!");
  }

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

ध्यान दें: onClick={handleClick} function pass करता है। onClick={handleClick()} लिखने पर function render के दौरान call हो सकता है।

Event Object

Code
function App() {
  function handleClick(event) {
    console.log(event.target);
  }

  return <button onClick={handleClick}>Inspect Button</button>;
}

React event handler को event object मिलता है, जिससे event target और दूसरी event details access की जा सकती हैं।

Input Change Event

Code
function SearchBox() {
  function handleChange(event) {
    console.log(event.target.value);
  }

  return <input type="text" onChange={handleChange} />;
}

Passing Arguments

Code
function App() {
  function handleDelete(id) {
    console.log("Delete item:", id);
  }

  return (
    <button onClick={() => handleDelete(101)}>
      Delete
    </button>
  );
}

इस approach से आप event handler को required arguments दे सकते हैं।

9. Conditional Rendering#

Conditional rendering का मतलब condition के आधार पर अलग UI दिखाना है।

if Statement

Code
function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h2>Welcome back!</h2>;
  }

  return <h2>Please log in</h2>;
}

Ternary Operator

Code
function App() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn ? <h2>Dashboard</h2> : <h2>Login</h2>}
    </div>
  );
}

Logical AND (&&)

Code
function Notifications({ count }) {
  return (
    <div>
      <h2>Notifications</h2>
      {count > 0 && <p>You have {count} notifications.</p>}
    </div>
  );
}

एक बात याद रखें: {count && <p>...</p>} लिखने पर अगर count zero है, तो कुछ situations में screen पर 0 render हो सकता है। इसलिए numeric condition के लिए {count > 0 && ...} अधिक स्पष्ट है।

10. Lists और Keys#

React में arrays के data को UI में दिखाने के लिए map() का उपयोग किया जाता है।

Basic List

Code
function App() {
  const fruits = ["Apple", "Banana", "Mango"];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}

Array of Objects

Code
function ProductList() {
  const products = [
    { id: 1, name: "Keyboard", price: 1200 },
    { id: 2, name: "Mouse", price: 500 },
    { id: 3, name: "Monitor", price: 8000 }
  ];

  return (
    <div>
      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>₹{product.price}</p>
        </div>
      ))}
    </div>
  );
}

key क्यों जरूरी है?

key React को list items की identity समझने में मदद करती है, खासकर जब items add, remove या reorder होते हैं।

Best practices:

  • Stable और unique ID को key बनाएँ।
  • Unnecessary array index को key न बनाएँ, खासकर बदलने वाली lists में।
  • Random key हर render पर generate न करें।
  • ध्यान रखें कि key prop सामान्य props की तरह child component को नहीं मिलता।

11. Forms और Controlled Components#

Forms में input values manage करने के लिए React state का उपयोग किया जा सकता है।

Controlled component में input की displayed value React state से control होती है।

Text Input

Code
import { useState } from "react";

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

  return (
    <div>
      <input
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)}
        placeholder="Enter your name"
      />

      <p>Your name: {name}</p>
    </div>
  );
}

export default NameForm;

Form Submit

Code
import { useState } from "react";

function LoginForm() {
  const [email, setEmail] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    console.log("Submitted email:", email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />

      <button type="submit">Submit</button>
    </form>
  );
}

event.preventDefault() browser के default form submission behavior को रोकता है। इसके बाद आप data validate करके API request कर सकते हैं।

Checkbox

Code
import { useState } from "react";

function TermsCheckbox() {
  const [accepted, setAccepted] = useState(false);

  return (
    <label>
      <input
        type="checkbox"
        checked={accepted}
        onChange={(event) => setAccepted(event.target.checked)}
      />
      I accept the terms
    </label>
  );
}

Text inputs में सामान्यतः value और checkboxes में checked property use की जाती है।

12. useEffect Hook#

useEffect का उपयोग component को external systems के साथ synchronize करने के लिए होता है। उदाहरण के लिए, browser event listener, network connection या किसी third-party system के साथ integration।

Basic Example

Code
import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Component effect ran");
  }, []);

  return <h1>Hello React</h1>;
}

Empty dependency array का अर्थ है कि Effect सामान्यतः component mount होने के बाद चलेगा। Development में Strict Mode अतिरिक्त setup-cleanup cycle चला सकता है।

Dependencies के साथ

Code
import { useEffect, useState } from "react";

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <button onClick={() => setCount((previous) => previous + 1)}>
      Count: {count}
    </button>
  );
}

जब count बदलता है, Effect document title को synchronize करता है।

Cleanup Function

Code
import { useEffect } from "react";

function TimerExample() {
  useEffect(() => {
    const timerId = setInterval(() => {
      console.log("Timer running");
    }, 1000);

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

  return <p>Timer example</p>;
}

Cleanup function timer को stop करता है, जिससे component हटने पर interval अनावश्यक रूप से चलता नहीं रहता।

useEffect कब नहीं use करना चाहिए?

हर calculation या event के लिए Effect की जरूरत नहीं होती।

उदाहरण के लिए, यदि fullName को firstName और lastName से calculate किया जा सकता है, तो उसे अलग state में रखने और Effect से update करने के बजाय सीधे calculate करें।

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

याद रखें: Effects external systems के synchronization के लिए हैं। केवल derived values calculate करने के लिए उनका unnecessary use न करें।

Official reference: React useEffect

13. Common React Hooks#

Hooks React function components को state और दूसरी React features use करने देते हैं।

HookPurpose
useStateComponent state manage करना
useEffectExternal systems के साथ synchronize करना
useContextContext से shared data read करना
useRefMutable value या DOM reference रखना
useReducerReducer के जरिए complex state updates manage करना
useMemoCalculation result cache करना
useCallbackFunction reference cache करना
useIdAccessibility-related IDs generate करना

useContext

Context कई levels के components तक data पहुँचाने में मदद करता है, बिना हर level पर props pass किए।

Code
import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function ThemeLabel() {
  const theme = useContext(ThemeContext);

  return <p>Current theme: {theme}</p>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemeLabel />
    </ThemeContext.Provider>
  );
}

export default App;

यह example Context का basic concept दिखाता है। Modern React में context setup के दूसरे patterns भी उपलब्ध हैं।

useRef

useRef ऐसी value रखने देता है जो re-render के बीच बनी रहती है। Ref बदलने से अपने आप component re-render नहीं होता।

Code
import { useRef } from "react";

function SearchBox() {
  const inputRef = useRef(null);

  function focusInput() {
    inputRef.current?.focus();
  }

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

यहाँ ref का उपयोग input element को focus करने के लिए किया गया है।

useReducer

जब state transitions कई प्रकार के हों, तो reducer pattern उपयोगी हो सकता है।

Code
import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };

    case "decrement":
      return { count: state.count - 1 };

    case "reset":
      return { count: 0 };

    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>{state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </div>
  );
}

useMemo

Expensive calculation के result को renders के बीच cache करने के लिए useMemo उपयोगी हो सकता है।

Code
import { useMemo } from "react";

function ProductList({ products, search }) {
  const filteredProducts = useMemo(() => {
    return products.filter((product) =>
      product.name.toLowerCase().includes(search.toLowerCase())
    );
  }, [products, search]);

  return (
    <ul>
      {filteredProducts.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

यह optimization हर छोटी calculation के लिए जरूरी नहीं है। पहले सही और readable code लिखें, फिर performance measurement के आधार पर optimization करें।

useCallback

Dependencies नहीं बदलने पर function reference cache करने के लिए useCallback use किया जा सकता है।

Code
import { useCallback, useState } from "react";

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

  const increment = useCallback(() => {
    setCount((previous) => previous + 1);
  }, []);

  return <button onClick={increment}>Count: {count}</button>;
}

यह example syntax दिखाता है। हर event handler को useCallback में wrap करने की जरूरत नहीं होती।

Hooks के rules:

  • Hooks को component या custom Hook के top level पर call करें।
  • Hooks को conditions, loops या nested functions के अंदर call न करें।
  • Function components और custom Hooks में Hooks use करें; regular utility functions में नहीं।

Official references: Built-in Hooks, useMemo, useCallback

14. API Calls और Fetch#

React applications अक्सर backend API से data fetch करती हैं। उदाहरण के लिए, product list, user profile या news feed load करना।

Basic Fetch Example

Code
import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function loadUsers() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

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

        const data = await response.json();
        setUsers(data);
      } catch (error) {
        if (error.name !== "AbortError") {
          setError(error.message || "Something went wrong");
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    loadUsers();

    return () => {
      controller.abort();
    };
  }, []);

  if (loading) return <p>Loading users...</p>;
  if (error) return <p>{error}</p>;

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default Users;

यह example loading, error और success states को handle करता है। Real application में API response के data को validate करना, pagination, retries और caching जैसी जरूरतें भी हो सकती हैं।

Important API Concepts

  • fetch() request भेजता है।
  • response.ok HTTP success status को check करने में मदद करता है।
  • response.json() JSON response को parse करता है।
  • try/catch errors handle करने में मदद करता है।
  • AbortController request को cancel करने में मदद कर सकता है।
  • Loading state user को request progress दिखाती है।

API Call करते समय Common Mistakes

  1. Loading state न रखना।
  2. Error handling छोड़ देना।
  3. हर response को success मान लेना।
  4. Component हटने के बाद भी unnecessary request चलने देना।
  5. API response के shape को बिना check किए assume करना।
  6. API keys या secrets को frontend code में expose करना।

Production applications में data fetching के लिए framework features या dedicated data-fetching libraries भी उपयोगी हो सकती हैं।

15. React Router और Navigation#

React Router का उपयोग React application में अलग-अलग URLs के लिए अलग pages render करने के लिए किया जा सकता है।

इसे install करें:

Code
npm install react-router

एक basic declarative setup:

Code
import {
  BrowserRouter,
  Routes,
  Route,
  Link
} from "react-router";

function Home() {
  return <h2>Home Page</h2>;
}

function About() {
  return <h2>About Page</h2>;
}

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

React Router के version और चुने गए setup के अनुसार imports और APIs अलग हो सकते हैं। अपने project में installed version की official documentation follow करें।

Important Routing Terms

TermPurpose
BrowserRouterBrowser-based routing setup
RoutesMatching route configuration
RouteURL path और element define करना
LinkClient-side navigation
Dynamic routeURL में variable segment
Nested routeParent route के अंदर child routes

Reference: React Router Documentation

16. React में Styling#

React components को style करने के कई तरीके हैं।

CSS Class

App.css:

Code
.card {
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.card-title {
  font-size: 20px;
}

App.jsx:

Code
import "./App.css";

function Card() {
  return (
    <div className="card">
      <h2 className="card-title">Product Card</h2>
    </div>
  );
}

export default Card;

Inline Styles

React में inline styles JavaScript object के रूप में लिखे जाते हैं।

Code
function App() {
  const titleStyle = {
    color: "blue",
    fontSize: "24px",
    marginTop: "16px"
  };

  return <h1 style={titleStyle}>Hello React</h1>;
}

Inline style properties सामान्यतः camelCase में लिखी जाती हैं, जैसे fontSize और marginTop।

Conditional Class

Code
function Button({ isActive }) {
  return (
    <button className={isActive ? "button active" : "button"}>
      Continue
    </button>
  );
}

बड़े projects में CSS Modules, utility CSS frameworks या CSS-in-JS libraries भी उपयोग की जा सकती हैं।

17. React में TypeScript#

आपने पिछले topic में TypeScript सीखा था। React के साथ TypeScript use करने से component props, state और API data के expected types स्पष्ट किए जा सकते हैं।

Typed Props

Code
interface UserProps {
  name: string;
  age: number;
  city?: string;
}

function UserCard({ name, age, city }: UserProps) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>City: {city ?? "Not provided"}</p>
    </div>
  );
}

export default UserCard;

Typed State

Code
import { useState } from "react";

type Status = "idle" | "loading" | "success" | "error";

function StatusMessage() {
  const [status, setStatus] = useState<Status>("idle");

  return (
    <button onClick={() => setStatus("loading")}>
      Current status: {status}
    </button>
  );
}

Typed Event

Code
import { useState } from "react";

function SearchInput() {
  const [query, setQuery] = useState("");

  function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    setQuery(event.target.value);
  }

  return <input value={query} onChange={handleChange} />;
}

इस syntax में React की types उपलब्ध होनी चाहिए, जैसा कि सामान्य React + TypeScript setup में होता है।

TypeScript के साथ React सीखने का सही क्रम

  1. Components और JSX
  2. Props और typed interfaces
  3. useState और state types
  4. Events और form handling
  5. useEffect और API data
  6. Reusable components और custom Hooks

18. Custom Hooks#

Custom Hook आपको reusable stateful logic को अलग function में रखने देता है। इसका नाम convention के अनुसार use से शुरू होता है।

Example:

Code
import { useState } from "react";

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  function toggle() {
    setValue((previous) => !previous);
  }

  return [value, toggle];
}

function App() {
  const [isOpen, toggleOpen] = useToggle(false);

  return (
    <div>
      <button onClick={toggleOpen}>
        {isOpen ? "Close" : "Open"}
      </button>

      {isOpen && <p>Panel content</p>}
    </div>
  );
}

export default App;

Custom Hook shared logic को reuse करने में मदद करता है। यह अपने आप UI component नहीं होता; UI component उसके returned values का उपयोग कर सकता है।

Custom Hooks के अंदर भी Hooks के rules follow करना जरूरी है।

19. React Performance Best Practices#

React application की performance improve करने के लिए पहले unnecessary work और expensive rendering को identify करें।

  1. Components छोटे और focused रखें: एक component में unrelated responsibilities इकट्ठी न करें।
  2. State को सही जगह रखें: Local state को unnecessarily top-level component तक न ले जाएँ।
  3. Stable keys use करें: Lists में stable IDs का उपयोग करें।
  4. Derived state avoid करें: जो value existing props या state से calculate हो सकती है, उसे duplicate state में न रखें।
  5. Unnecessary Effects हटाएँ: Effects से होने वाली extra render chains को avoid करें।
  6. Memoization जरूरत के अनुसार करें: useMemo, useCallback और memo को बिना वजह हर जगह use न करें।
  7. Large lists पर ध्यान दें: बहुत बड़ी lists के लिए pagination या virtualization पर विचार करें।
  8. Production build test करें: Development और production behavior अलग हो सकते हैं।
  9. React Developer Tools use करें: Component tree और rendering behavior inspect करें।
  10. Network requests optimize करें: Unnecessary requests और duplicate data fetching कम करें।

React Compiler कुछ supported configurations में automatic memoization कर सकता है। फिर भी performance के लिए measurement, correct state design और clean rendering logic महत्वपूर्ण हैं।

20. React Security Basics#

React UI बनाने में मदद करता है, लेकिन application security की पूरी जिम्मेदारी React की नहीं होती।

Important Practices

  • User input को validate करें।
  • Backend पर authorization और permissions enforce करें।
  • Secrets और private API keys frontend bundle में न रखें।
  • Authentication tokens और sensitive data को carefully handle करें।
  • Untrusted HTML को सीधे render करने से बचें।
  • dangerouslySetInnerHTML का उपयोग केवल carefully sanitized content के साथ करें।
  • API errors में sensitive server details expose न करें।

React सामान्य JSX text interpolation को escape करता है, लेकिन इसका मतलब यह नहीं कि हर प्रकार का input और integration अपने आप सुरक्षित हो जाता है।

21. Common React Mistakes#

Mistake 1: Component Name lowercase रखना

Code
function profileCard() {
  return <div>Profile</div>;
}

Better:

Code
function ProfileCard() {
  return <div>Profile</div>;
}

React components को capital letter से शुरू करें।

Mistake 2: Event Handler को तुरंत Call करना

Code
<button onClick={handleClick()}>Click</button>

अगर handler को click पर call करना है, तो:

Code
<button onClick={handleClick}>Click</button>

Mistake 3: State को Directly Modify करना

Code
items.push(newItem);

अगर items React state है, तो array को mutate न करें।

Code
setItems((previousItems) => [...previousItems, newItem]);

Mistake 4: List में key न देना

Code
items.map((item) => <li>{item.name}</li>)

Better:

Code
items.map((item) => <li key={item.id}>{item.name}</li>)

Mistake 5: Hook को Condition के अंदर Call करना

Code
if (isLoggedIn) {
  const [name, setName] = useState("");
}

Hooks को component के top level पर call करें।

Mistake 6: हर चीज के लिए useEffect Use करना

अगर value सीधे props या state से calculate हो सकती है, तो उसे अलग Effect से sync करने की जरूरत अक्सर नहीं होती।

Mistake 7: API Error Handle न करना

सिर्फ fetch() call करने से complete error handling नहीं होती। HTTP status, network failures, loading state और response data को handle करें।

Mistake 8: Props को Modify करना

Props read-only inputs हैं। Value बदलने के लिए parent state या callback pattern use करें।

22. React Quick Reference#

SyntaxPurpose
function App() {}Function component
export default AppDefault export
import App from "./App"Default import
<Header />Component render करना
<h1>{name}</h1>JSX में expression
className="card"CSS class
onClick={handleClick}Click handler
useState(0)State create करना
setCount(c => c + 1)Previous state के आधार पर update
useEffect(() => {}, [])Mount के बाद Effect चलाना
useRef(null)Ref create करना
useContext(MyContext)Context read करना
useReducer(reducer, initialState)Reducer-based state
useMemo(() => value, [deps])Calculation cache करना
useCallback(fn, [deps])Function reference cache करना
items.map(...)List render करना
key={item.id}List item identity
condition ? A : BConditional rendering
{condition && <UI />}Condition true होने पर UI
event.preventDefault()Default browser behavior रोकना
fetch(url)HTTP request करना
<Link to="/about">React Router navigation
npm run devDevelopment server
npm run buildProduction build

23. Knowledge Check#

Q1. React का मुख्य उपयोग क्या है?

A. Database manage करना
B. User interfaces बनाना
C. Server configure करना
D. Operating system install करना

Q2. React में component state manage करने के लिए कौन-सा Hook use होता है?

A. useState
B. useRoute
C. useHTML
D. useCSS

Q3. Props का उपयोग मुख्य रूप से किसलिए होता है?

A. Parent से child component तक data pass करने के लिए
B. Database delete करने के लिए
C. CSS compile करने के लिए
D. Server restart करने के लिए

Q4. React list में key क्यों जरूरी है?

A. Font size बदलने के लिए
B. List items की identity समझने के लिए
C. API key store करने के लिए
D. Browser cache clear करने के लिए

Q5. useEffect का मुख्य उपयोग क्या है?

A. सभी CSS styles लिखना
B. External systems के साथ synchronize करना
C. HTML file create करना
D. TypeScript install करना

Q6. React में state array को update करने का बेहतर तरीका कौन-सा है?

A. Existing array को mutate करना
B. New array बनाकर setter को देना
C. State setter को कभी use न करना
D. Props modify करना

Answers: 1-B, 2-A, 3-A, 4-B, 5-B, 6-B.

24. Practice Exercises#

Exercise 1: Profile Card

एक ProfileCard component बनाएँ जिसमें name, job title और city props के जरिए pass हों।

कम से कम तीन अलग-अलग profiles render करें।

Exercise 2: Counter App

एक counter बनाएँ जिसमें ये buttons हों:

  • Increase
  • Decrease
  • Reset

Counter zero से शुरू होना चाहिए।

Exercise 3: Todo List

एक simple Todo application बनाएँ जिसमें user:

  • नया task add कर सके।
  • Task complete mark कर सके।
  • Task delete कर सके।
  • Empty input submit न कर सके।

Todo items को React state में रखें और stable IDs को keys के रूप में use करें।

Exercise 4: Product Filter

एक product array बनाएँ जिसमें id, name और price हों।

एक search input और price filter बनाएँ, ताकि user products को name और price के आधार पर filter कर सके।

Exercise 5: API Integration

किसी public test API से data fetch करें। UI में ये states दिखाएँ:

  • Loading
  • Error
  • Success

Request failure और component cleanup को भी handle करें।

Exercise 6: React + TypeScript

Exercise 1 के Profile Card को TypeScript में convert करें। Props के लिए interface या type define करें और optional city property support करें।

25. Summary#

इस React Cheat Sheet में आपने सीखा:

  • React क्या है और इसका उपयोग क्यों होता है।
  • Vite से React project setup करना।
  • JSX और function components।
  • Props और state।
  • useState, useEffect, useContext, useRef और useReducer।
  • Event handling और conditional rendering।
  • Lists और keys।
  • Forms और controlled components।
  • API integration और error handling।
  • React Router से navigation।
  • CSS styling और React + TypeScript।
  • Custom Hooks, performance और security basics।
  • Common mistakes और quick reference।

Short में: React में reusable components UI बनाते हैं, props components के बीच data pass करते हैं और state बदलने पर React UI को update कर सकता है। इन fundamentals को अच्छी तरह समझने के बाद आप real-world frontend applications बनाना शुरू कर सकते हैं।

26. सीखें#

आपकी learning path में React, JavaScript Ecosystem का अगला practical topic है। React के बाद आप PHP backend और database topics को जोड़कर full-stack development की दिशा में आगे बढ़ सकते हैं।

Suggested learning order:

  1. JavaScript Cheat Sheet
  2. JSON Cheat Sheet
  3. Fetch / REST APIs Cheat Sheet
  4. Build Tools (Vite) Cheat Sheet
  5. TypeScript Cheat Sheet