
--- PDF page 230 ---
U N I T 4 · F R O N T- E N D W I T H R E A C T. J S




       04
       React.js — Components to Server
       Components
       From your first line of JSX to a React app that talks to Django REST — and then the part
       your notes skip completely: where React code actually runs (browser, server, or both).
       Every concept is built on the ShopLite code-along you already have, and every React ques‐
       tion from the last three papers is answered in full, ready to copy into the answer sheet.

          99 marks asked in 3 papers        14 PYQs solved      3 gaps filled (G1 · G3 · G12)


          Final 2025-26: all of Q2 + Q4 are React




  ✍️ WHY THIS UNIT DECIDES YOUR GRADE
  In the newest paper (Dec 2025), React carried 49 of 100 marks: Q1(a), Q1(b), the whole of Q2 (state, ef‐
  fects, lifting state) and the whole of Q4 (RSC vs CSR vs SSR, SPA vs RSC, Django's role). Q4 is 20 marks
  your study material does not cover at all — sections 4.18 to 4.20 teach it from zero. If you master this
  chapter you can pick Q2 and Q4 with confidence.



   4.1 Why React — Virtual DOM, component tree                     4.12 Hook programs: counter apps
   4.2 Setting up a project with Vite                              4.13 Context API
   4.3 JSX                                                         4.14 useReducer and Context + Reducer
   4.4 Components — function and class                             4.15 API handling
   4.5 Props                                                       4.16 CRUD from React to Django REST
   4.6 State and useState                                          4.17 Backend connectivity and auth
   4.7 Props vs state                                              4.18 CSR, SSR, SSG and RSC
   4.8 Batching and functional updates                             4.19 SPA vs RSC
   4.9 Lifting state up                                            4.20 Django behind an SPA vs an RSC app
   4.10 Hooks and the rules of hooks                               4.21 Common mistakes and fixes
   4.11 useEffect in depth                                         4.22 Likely questions for 2026
                                                                   4.23 Last-minute recap



 Topic                                  Final 2025-26          Final 2024-25     Re-Exam 2023-24         In your files?

 JSX                                    —                      Q1(a) 5 M         —                        covered


 Components, class vs function          —                      —                 Q6(a) 10 M               class part = gap G12

--- PDF page 231 ---
Topic                                  Final 2025-26            Final 2024-25    Re-Exam 2023-24          In your files?

 Props / passing data                   Q1(a) 4 M                Q7(b) 10 M       Q7(a) 10 M                covered

 State, hooks, counter                  Q1(b) 5 M, Q2(B) 6 M     Q5(b) 10 M       Q1(c) 5 M                 covered


 Batching, functional updates           Q2(A) 8 M                —                —                         gap G3

 Lifting state up                       Q2(C) 6 M                —                —                         covered (thin)


 RSC vs CSR vs SSR, SPA, Django         Q4 A+B+C 20 M            —                —                         gap G1 — zero coverage




    4.1 Why React — Virtual DOM and the component tree
📚 Sources: Unit 4 Notes §1      LEC 9 (React) s.3–5   ShopLite React Manual 1.1   One-Shot p.13      Complete Revision deck s.31


  🧠 START FROM ZERO
  React is a JavaScript library for building user interfaces, made by Meta (Facebook). You split the screen
  into small reusable pieces called components. Each component is a JavaScript function that says what its
  piece of the screen should look like for the current data. When the data changes, React works out what
  changed and updates the page for you.



▸ Plain HTML + CSS + JS vs React
For one or two pages, plain HTML, CSS and JavaScript is fine. In a big app you end up hunting DOM nodes by
hand ( document.getElementById ), editing them, and keeping your variables and the screen in sync yourself.
React removes that work.

  Aspect                        HTML + CSS + JS                                   React

  Building the UI               Separate pages of markup                          Reusable components

  Updating the screen           Find DOM nodes and edit them by hand              Change state, React updates the UI

  Code reuse                    Copy-paste the same markup                        Write once, reuse with props

  Data handling                 Scattered variables and DOM reads                 Centralised state, one-way data flow

  Large apps                    Hard to maintain                                  Organised as a component tree

  Style of code                 Imperative — how to do it                         Declarative — what it should look like

  Ecosystem                     Build your own tooling                            Router, hooks, DevTools, huge community



▸ Imperative vs declarative — the favourite comparison

           imperative — counter.js (plain JS): you say HOW


  let count = 0;
  const btn = document.getElementById("btn");

--- PDF page 232 ---
const label = document.getElementById("label");


  btn.addEventListener("click", () => {
      count = count + 1;
      label.textContent = `Clicked ${count} times`;                // YOU update the DOM, every time
  });



           declarative — Counter.jsx (React): you say WHAT


  import { useState } from "react";


  function Counter() {
      const [count, setCount] = useState(0);
      // just describe the UI for this count; React does the DOM work
      return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
  }




▸ How React updates the screen: Virtual DOM, diff, patch
The DOM (Document Object Model) is the browser's live tree of page elements; touching it is slow because the
browser may re-calculate layout and repaint. React keeps a lightweight copy of the UI in memory, the Virtual
DOM — plain JavaScript objects describing elements.

               State changes             New Virtual DOM                        Diff                 Patch real DOM
               click, data arrives
                                     →   component re-runs
                                                               →         old tree vs new tree
                                                                                                →   only changed nodes



The diffing step is called reconciliation. React compares the old and new trees with two cheap rules: (1) if an
element's type changed (say div became section , or Login became Dashboard ) it throws away that sub‐
tree and builds a new one; (2) if the type is the same it only updates the changed attributes and recurses into
children. For lists it uses the key prop to match old items with new ones. The result: only the nodes that actu‐
ally changed touch the real DOM .

RENDER AND COMMIT — THE VOCABULARY YOU WILL NEED FOR USEEFFECT

 1        Trigger. The first render (app starts) or a state update ( setCount ).

 2        Render phase. React calls your component functions to get the new JSX (the Virtual DOM). Pure calcu‐
          lation — nothing on screen changes yet.

 3        Commit phase. React applies the minimal set of changes to the real DOM.

 4        Browser paint, then effects. The browser draws the pixels; React then runs your useEffect code.
          This is why the notes say "useEffect runs after render".

--- PDF page 233 ---
▸ A React app is a tree of components

                                                                       App



                         Header                                        Main                                       Footer



                                                ProductList                                 Cart                   data flows DOWN
                                                                                                                       as props


                        ProductCard             ProductCard              ProductCard


                          The ShopLite tree (Unit 4 Notes §2.3): ProductCard is written once and reused for every product.


  🔑 MEMORY HOOK — THE THREE WORDS
  C-D-V: Component-based (split UI into reusable pieces) · Declarative (describe what, not how) · Virtual
  DOM (diff in memory, patch only what changed). Write these three in any "Why React?" answer.




    4.2 Setting up a React project with Vite
📚 Sources: ShopLite React Manual 0.1–0.3, 5.1          Unit 4 Notes §2.1, §15

 Not in your files — create-vite commands added from standard references


The browser cannot read JSX, so every React project needs a build tool that compiles it. Your course uses Vite
(French for "fast"): a dev server with instant reload, plus a production bundler. You need Node.js (Node 20.19+
— 22 LTS is best) and npm, which comes with it.

           terminal — create, run, build


  node --version                         # check tools (manual step 0.1)
  npm --version


  npm create vite@latest shoplite -- --template react                            # scaffold a React project
  cd shoplite
  npm install                            # download dependencies into node_modules/
  npm run dev                            # dev server on http://localhost:5173 (hot reload)


  npm install axios                      # extra library used in ShopLite Part 4
  npm run build                          # production build -> dist/ (plain HTML, CSS, JS)
  npm run preview                        # serve the built dist/ locally to test it


The ShopLite starter is already scaffolded, so the manual only runs npm install and npm run dev inside
 shoplite/frontend .

--- PDF page 234 ---
▸ Folder structure (ShopLite after Part 5)

           shoplite/frontend/


  frontend/
  ├── index.html                ← the ONE html page: contains <div id="root"></div>
  ├── package.json              ← dependencies + scripts (dev, build, preview)
  ├── vite.config.js            ← Vite settings (React plugin, port, dev proxy)
  ├── .env                      ← VITE_API_URL=http://localhost:8000/api
  ├── node_modules/             ← installed libraries (never commit)
  └── src/
        ├── main.jsx            ← entry point: mounts <App /> into #root
        ├── App.jsx             ← root component
        ├── api.js              ← one configured axios client
        ├── styles.css
        ├── data/products.js    ← 8 sample products (Parts 1–3)
        ├── components/         ← Header, ProductCard, ProductList, Cart, AddProductForm
        └── context/            ← cartReducer.js, CartContext.jsx



           index.html


  <!doctype html>
  <html lang="en">
     <head>
        <meta charset="UTF-8" />
        <title>ShopLite</title>
     </head>
     <body>
        <div id="root"></div>
        <script type="module" src="/src/main.jsx"></script>
     </body>
  </html>



           src/main.jsx (ShopLite manual, step 3.2)


  import { StrictMode } from "react";
  import { createRoot } from "react-dom/client";
  import App from "./App.jsx";
  import { CartProvider } from "./context/CartContext.jsx";
  import "./styles.css";


  createRoot(document.getElementById("root")).render(
     <StrictMode>
        <CartProvider>
           <App />
        </CartProvider>

--- PDF page 235 ---
</StrictMode>
  );



 createRoot(...).render(...) is the line that starts React in the browser: it takes over the empty #root div
and draws App inside it. <StrictMode> is a development-only helper: it renders components and runs effects
twice on first load to expose bugs, which is why the Network tab shows two requests in development and one in
production.

  ⚠️ COMMON LAB PROBLEMS (MANUAL TROUBLESHOOTING)
         node --version still fails after installing → close the terminal and open a new one.

        Vite starts on port 5174 → another process holds 5173, and Django's CORS list no longer matches.
        Stop the other server.
        Changed .env and nothing happened → Vite reads .env only at startup; restart npm run dev .
        PowerShell: "running scripts is disabled" → Set-ExecutionPolicy -Scope Process RemoteSigned , or
        use Command Prompt.



   ✏️ COMMAND COMPLETION
    1. Scaffold a React app with Vite:
         npm create                      @latest shoplite -- --template

    2. Download the project's dependencies: npm
    3. Start the dev server (port 5173): npm run
    4. Make the production build in dist/ : npm run
    5. The div React mounts into: <div id="                               "> ; the function that mounts it:
                        (document.getElementById("root")).render(<App />)


   🔓 Answer key: 1) vite · react 2) install 3) dev 4) build 5) root · createRoot


    4.3 JSX — HTML-like syntax inside JavaScript
📚 Sources: Unit 4 Notes §2         LEC 9 (React) s.6–7, s.9    ShopLite React Manual 1.1, 1.3   One-Shot p.13

 Complete Revision deck s.31


JSX (JavaScript XML) is a syntax extension that lets you write HTML-like markup inside JavaScript. The markup
sits next to the logic it belongs to.

            Welcome.jsx (Unit 4 Notes §2.1)


  function Welcome() {
       const name = "Asha";
       return (
        <h1 className="title">
           Hello, {name}!
        </h1>

--- PDF page 236 ---
);
  }




▸ What happens to JSX before the browser sees it

             JSX            Vite / Babel          createElement() calls             JS objects
           you write
                        →      compiles
                                           →              plain JS
                                                                             →      Virtual DOM
                                                                                                     →       Browser DOM



             you write (JSX)


  const el = <h1 className="title">Hello, {name}!</h1>;



             the compiler produces (classic form)


  const el = React.createElement("h1", { className: "title" }, "Hello, ", name, "!");


Since React 17 the compiler emits the equivalent jsx() function from react/jsx-runtime , which is why modern files no
longer need import React from "react" . Either way, JSX is just syntax sugar for function calls that return plain objects .



▸ JSX rules — what changes from HTML

  HTML                         JSX                                   Why

   class="box"                  className="box"                      class is a reserved word in JavaScript

   for="email"                  htmlFor="email"                      for is a JavaScript keyword

   onclick="save()"             onClick={save}                       camelCase event names; pass a function

   <img> <br>                   <img /> <br />                       Every tag must be closed

   style="color:red"            style={{ color: "red" }}             Style is a JavaScript object (camelCase keys: fontSize )

  Two sibling roots             <> ... </> (Fragment)                A component returns exactly one root

  Static text only              {user.name}                          { } embeds any JS expression

   <!-- comment -->             {/* comment */}                      Comments are JS comments inside braces



  ⚠️ DOUBLE BRACES
    style={{ color: "red" }} has two pairs of braces for two different reasons: the outer pair means
  "JavaScript goes here", the inner pair is the object literal. And { } takes expressions only — you can
  write a ternary {a ? b : c} but not an if statement or a for loop.

--- PDF page 237 ---
▸ Lists, conditions and events — the three everyday patterns

  Pattern             Code                                                        Note

  List                {items.map(i => <li key={i.id}>{i.name}</li>)}              Each item needs a unique, stable key

  If / else           {loggedIn ? <Dashboard /> : <Login />}                      Ternary picks one of two

  Show / hide         {error && <p>{error}</p>}                                   Renders only when the left side is true

  Event               <button onClick={handleSave}>Save</button>                  Pass the function, do not call it


The manual's ProductCard (step 1.3) uses all three in one component:

              src/components/ProductCard.jsx (manual step 1.3)


  export default function ProductCard({ product }) {
      const { name, price, category, in_stock } = product;


      function handleAdd() {
          console.log("Add to cart:", name);
      }


      return (
          <article className="card">
              <span className="tag">{category}</span>
              <h3>{name}</h3>
              <p className="price">₹{price.toLocaleString("en-IN")}</p>
              {price > 5000 && <span className="tag">Free delivery</span>}
              {in_stock ? (
                <span className="stock in">In stock</span>
              ) : (
                <span className="stock out">Out of stock</span>
              )}
              <button className="btn" disabled={!in_stock} onClick={handleAdd}>
                Add to cart
              </button>
          </article>
      );
  }



  ⚠️ TWO CLASSIC MISTAKES (MANUAL "DO TRY" BOXES)
          No key in a list → console warning "Each child in a list should have a unique key" and wrong re-ren‐
          ders. Use a stable id from the data, not the array index, when the list can be reordered or filtered.
           onClick={handleAdd()} calls the function during rendering (once per card) instead of on click. Write
           onClick={handleAdd} , or onClick={() => onAdd(product)} when you need an argument.

          Deleting the <> wrapper → "Adjacent JSX elements must be wrapped in an enclosing tag".

--- PDF page 238 ---
PYQ          Final 2024-25 · Q1(a)                                                                                           5M


  What is JSX? What are its Key Features?

   ✓       MODEL ANSWER — WRITE THIS

  JSX (JavaScript XML) is a syntax extension to JavaScript used in React that lets us write HTML-like
  markup directly inside JavaScript code to describe what the UI should look like. The browser cannot under‐
  stand JSX, so a build tool (Babel / Vite) compiles it into plain JavaScript React.createElement() calls,
  which produce JavaScript objects (the Virtual DOM) that React renders to the real DOM.

                 example


       function Welcome() {
           const name = "Asha";
           return <h1 className="title">Hello, {name}!</h1>;
       }
       // compiles to: React.createElement("h1", { className: "title" }, "Hello, ", name, "!")



  KEY FEATURES

    1. HTML-like and declarative — markup sits next to the logic it belongs to, so the UI is easy to read.
    2. Embedded JavaScript expressions with { } — variables, function calls, maths, ternaries: {2 + 3} ,
           {user.name} .

    3. Compiled, not interpreted — converted to createElement() calls; errors are caught at build time.
    4. Attributes in camelCase — className , htmlFor , onClick ; inline style is an object:
           style={{ color: "red" }} .

    5. Single root element — a component returns one root; use a Fragment <>…</> to group siblings.
    6. Every tag must be closed — <img /> , <br /> .
    7. Conditional rendering and lists — {ok ? <A /> : <B />} , {error && <p>…</p>} ,
           {items.map(i => <li key={i.id}>…</li>)} .

    8. Safe by default — embedded values are escaped before rendering, which helps prevent XSS (injection)
           attacks.
    9. Components as tags — custom components are used like HTML tags ( <Card title="HTML" /> ) and
           must start with a capital letter.

  🎯 Marking scheme guess: 1 M definition · 1 M compilation (Babel/createElement) · 3 M for 5–6 features with mini-examples

   ✏️ FIX THE JSX — 6 ERRORS
   This is "HTML pasted into a component". Rewrite each marked line as valid JSX.

                 LoginBox.jsx — broken


       function loginBox() {                                               // (1)
            return (
              <h2 class="heading">Login</h2>                                  // (2)

--- PDF page 239 ---
<label for="email">Email</label>                                  // (3) + (4) two roots
                <input id="email" style="border: 1px solid red">                  // (5)
                <button onclick="login()">Go</button>                             // (6)
            );
       }



   🔓 Answer key: (1) Component name must be PascalCase: LoginBox · (2) className="heading" · (3)
      htmlFor="email" · (4) wrap the siblings in <>…</> · (5)
      <input id="email" style={{ border: "1px solid red" }} /> (object style + self-closing) · (6)
      onClick={login} — camelCase and pass the function.




      4.4 Components — function and class
📚 Sources: Unit 4 Notes §3        LEC 9 (React) s.8   ShopLite React Manual 1.2     One-Shot p.13

 Class components: not in your files — added from standard references


A component is an independent, reusable piece of UI. Technically it is a JavaScript function (or class) that takes
input data called props and returns JSX describing what should appear on screen. Small components combine
into bigger screens — this is called composition.

                 Card.jsx + App.jsx (Unit 4 Notes §3)


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


  function App() {
       return (
           <>
             <Card title="HTML" />
             <Card title="CSS" />
           </>
       );
  }



  Part                          Role

  Name (PascalCase)             The function name is the tag name: <Card /> . <card /> (lowercase) is treated as a plain
                                HTML tag.

  Props (parameter)             Input data from the parent, received as one object (usually destructured)

  Logic (above re‐              State, event handlers, calculations
  turn )

  JSX ( return )                What the component renders

--- PDF page 240 ---
Each component normally lives in its own file under src/components/ and is shared with export default /
 import — the manual (step 1.2) creates Header.jsx and ProductCard.jsx this way and composes them in
 App.jsx : one ProductCard , written once, used three times with different props
( <ProductCard name="Wireless Mouse" price={799} /> ).


▸ Two ways to write a component
React has two kinds of component. Function components are plain functions and use hooks for state and side
effects — this is what your notes, the manual and all modern code use. Class components are the older ES6-
class style (before hooks arrived in React 16.8, 2019) and are still asked in exams and found in older codebases.

     🚨 NOT IN YOUR STUDY MATERIAL · 10 MARKS · RE-EXAM 2023-24 Q6(A)
     Gap G12. The question asks for "Class component and Function component with coding example". Your
     notes, slides and manual teach only function components — none of your 22 study files show a class
     component ( extends React.Component , this.state , this.setState , lifecycle methods).

     Verdict: MUST LEARN (about 30 minutes). It is a full 10-mark question, the class syntax is short and pre‐
     dictable, and the lifecycle-to-useEffect mapping also strengthens your useEffect answers (Final 2025-26
     Q1b, Q2B). Everything you need is below.



▸ Class components from zero

 1        Extend Component . class Counter extends React.Component (or
           import { Component } from "react" ). This gives the class this.props , this.state and
           this.setState .


 2        Constructor. constructor(props) { super(props); … } — super(props) must be called first, oth‐
          erwise this is not ready. Initialise state here: this.state = { count: 0 } (state in a class is always
          one object).

 3        Read props and state with this . this.props.title , this.state.count .

 4        Update with this.setState() . Never assign this.state.count = 5 after the constructor.
           setState merges the object you pass into the existing state (other keys are kept), is batched and
          asynchronous like the useState setter, has an updater form
           this.setState(prev => ({ count: prev.count + 1 })) , and an optional callback that runs after the
          update is applied: this.setState({ count: 1 }, () => console.log(this.state.count)) .

 5         render() is required. It returns the JSX. It must be pure — no setState, no fetching.


 6        Bind event handlers. Class methods lose this when passed as callbacks, so bind them in the con‐
          structor ( this.increment = this.increment.bind(this) ) or write them as arrow class fields
          ( increment = () => { … } ).

--- PDF page 241 ---
▸ The lifecycle methods

                          MOUNTING                                                   UPDATING
             constructor → render → componentDidMount
                                                          →       new props / setState → render → componentDidUpdate
                                                                                                                          →

                                                           UNMOUNTING
                                                        componentWillUnmount



  Lifecycle method                    When it runs                 Typical use                        Hook equivalent

   constructor(props)                 Once, before the first       Initialise this.state ,              useState(initial)
                                      render                       bind handlers

   render()                           Every render                 Return JSX                         The function body's re‐
                                                                                                      turn

   componentDidMount()                Once, after the first        Fetch data, start timers,            useEffect(fn, [])
                                      render is on screen          subscriptions

   componentDidUpdate(prev‐           After every re-render        React to a change — com‐             useEffect(fn, [dep])
  Props, prevState)                   (not the first)              pare with prev… first

   componentWillUnmount()             Just before the com‐         Clear timers, cancel re‐           The cleanup function re‐
                                      ponent is removed            quests, unsubscribe                turned from useEffect

   shouldComponentUpdate()            Before a re-render           Skip unnecessary renders             React.memo

   componentDidCatch()                When a child throws          Error boundary (fallback UI)       No hook — error boundaries
                                      during render                                                   are still classes



  🧠 WHY HOOKS REPLACED CLASSES
  Compare the two counters in the model answer below. The function version has no this , no binding, no
  constructor, and a timer's start and stop sit together in one useEffect instead of being split across
    componentDidMount and componentWillUnmount . Logic can also be reused through custom hooks.
  Same UI, roughly 40% less code.



▸ Function vs class — the comparison table

  Point                 Function component                             Class component

  Syntax                Plain JS function returning JSX                ES6 class extends React.Component with a ren‐
                                                                       der() method

  Props                 Function parameter: ({ title })                 this.props.title

  State                  useState — any number of separate              this.state — one object, set in the constructor
                        values

  Updating state        Setter replaces the value:                      this.setState() merges into the object
                         setCount(5)

--- PDF page 242 ---
Point                   Function component                    Class component

  Side effects /           useEffect (mount, update, cleanup     componentDidMount , componentDidUpdate ,
  lifecycle               in one place)                          componentWillUnmount

   this keyword           Not used                              Everywhere; handlers need binding

  Reusing logic           Custom hooks ( useFetch , use‐        Higher-order components / render props (clumsier)
                          Cart )

  Code size               Short                                 Longer, more boilerplate

  Status today            Recommended for all new code          Still supported; needed only for error boundaries



   PYQ        Re-Exam 2023-24 · Q6(a)                                                                                  10 M


  What are React components? Explain Class component and Function component with coding
  example.

   ✓    MODEL ANSWER — WRITE THIS


  1. DEFINITION

  A React component is an independent, reusable building block of the user interface. It is a JavaScript
  function or class that accepts inputs called props and returns JSX (React elements) describing what should
  appear on the screen. A React application is a tree of components (App → Header, ProductList →
  ProductCard …); data flows down the tree as props. Component names must start with a capital letter
  ( <Card /> ), and a component returns a single root element.

  Advantages: reusability (write once, use many times with different props), separation of concerns (each
  piece of UI in its own file), easier testing and maintenance, and composition (small components combine
  into whole pages).

  2. FUNCTION COMPONENT
  A plain JavaScript function that receives props as its parameter and returns JSX. Since React 16.8 it can
  hold state and side effects through hooks ( useState , useEffect ). It is the modern, recommended style.

               FunctionCounter.jsx


       import { useState, useEffect } from "react";


       function FunctionCounter({ title }) {                         // props as parameter
          const [count, setCount] = useState(0);                 // state
          const [seconds, setSeconds] = useState(0);


          useEffect(() => {                                      // mount: start timer
           const id = setInterval(() => setSeconds((s) => s + 1), 1000);
           return () => clearInterval(id);                       // unmount: cleanup
          }, []);

--- PDF page 243 ---
useEffect(() => {                                    // runs when count changes
             document.title = `Count: ${count}`;
         }, [count]);


         return (
             <div>
                 <h2>{title}</h2>
                 <p>Count: {count} · Seconds: {seconds}</p>
                 <button onClick={() => setCount(count + 1)}>Increment</button>
             </div>
         );
     }
     export default FunctionCounter;



  3. CLASS COMPONENT

  An ES6 class that extends React.Component and must define a render() method returning JSX. Props
  are read with this.props ; state is an object created in the constructor ( this.state ) and changed only
  with this.setState() , which merges the change and re-renders. It has lifecycle methods:
    componentDidMount (after first render), componentDidUpdate (after updates) and
    componentWillUnmount (before removal).

                 ClassCounter.jsx


     import React from "react";


     class ClassCounter extends React.Component {
         constructor(props) {
             super(props);                          // call parent constructor first
             this.state = { count: 0, seconds: 0 };     // initial state (one object)
         }


         componentDidMount() {                      // lifecycle: after first render
             document.title = `Count: ${this.state.count}`;
             this.id = setInterval(() =>
                 this.setState((prev) => ({ seconds: prev.seconds + 1 })), 1000);
         }


         componentDidUpdate(prevProps, prevState) {       // lifecycle: after updates
             if (prevState.count !== this.state.count) {
                 document.title = `Count: ${this.state.count}`;
             }
         }


         componentWillUnmount() {                   // lifecycle: before removal
             clearInterval(this.id);
         }

--- PDF page 244 ---
increment = () => {                             // arrow field keeps "this"
             this.setState((prev) => ({ count: prev.count + 1 }));           // merges; seconds kept
         };


         render() {                                      // required
             return (
              <div>
                   <h2>{this.props.title}</h2>
                   <p>Count: {this.state.count} · Seconds: {this.state.seconds}</p>
                   <button onClick={this.increment}>Increment</button>
              </div>
             );
         }
     }
     export default ClassCounter;



                  App.jsx — usage


     import FunctionCounter from "./FunctionCounter";
     import ClassCounter from "./ClassCounter";


     export default function App() {
         return (
             <>
              <FunctionCounter title="Function Component" />
              <ClassCounter title="Class Component" />
             </>
         );
     }



                  Output (5 s after loading, each Increment clicked twice)


     Function Component
     Count: 2 · Seconds: 5
     [ Increment ]
     Class Component
     Count: 2 · Seconds: 5
     [ Increment ]



  4. DIFFERENCE

    Point               Function component                 Class component

    Definition          JS function returning JSX          Class extending React.Component with render()

    Props               Parameter props / destructured      this.props

--- PDF page 245 ---
Point               Function component                          Class component

    State                useState hook                               this.state + this.setState()

    Lifecycle            useEffect                                   componentDidMount/DidUpdate/WillUnmount

     this               Not needed                                  Required; handlers must be bound

    Code                Shorter, easier to test                     More boilerplate

    Usage today         Recommended                                 Legacy code, error boundaries


  Conclusion: both kinds produce the same UI; function components with hooks are shorter, avoid this ,
  and keep related logic together, so they are the standard in modern React, while class components remain
  important for reading older code.

  🎯 Marking scheme guess: 2 M definition + advantages · 3 M function component with code · 3 M class component with state/lifecycle
  code · 2 M comparison table + conclusion




   ✏️ FILL IN THE BLANKS — CLASS COMPONEN T
                Timer.jsx


     import React from "react";


     class Timer extends React.__(1)__ {
         constructor(props) {
             __(2)__(props);
             this.__(3)__ = { seconds: 0 };
         }
         componentDidMount() {
             this.id = setInterval(() =>
              this.__(4)__((prev) => ({ seconds: prev.seconds + 1 })), 1000);
         }
         __(5)__() {
             clearInterval(this.id);                       // stop the timer before removal
         }
         __(6)__() {
             return <p>{this.props.label}: {this.state.seconds}s</p>;
         }
     }



   🔓 Answer key: (1) Component · (2) super · (3) state · (4) setState · (5) componentWillUnmount · (6) render. Hook version of (4)+(5):
    useEffect(() => { const id = setInterval(…); return () => clearInterval(id); }, [])




    4.5 Props — passing data between components
📚 Sources: Unit 4 Notes §4        LEC 9 (React) s.10    ShopLite React Manual 1.2, 1.3, 2.2   One-Shot p.13

--- PDF page 246 ---
Complete Revision deck s.32


  🧠 START FROM ZERO
  Props (short for properties) are the inputs of a component. The parent writes them like HTML attributes; the
  child receives them as one object (its function parameter). Props are to a component what arguments are
  to a function.


                                 Parent         →                       Child        →            UI
                               owns the data    props: name, age   receives props    renders   "Asha, 21"



           Parent and child (Unit 4 Notes §4)


  // Parent
  function App() {
      return <UserCard name="Asha" age={21} />;
  }


  // Child — props arrive as ONE object; destructuring pulls out the fields
  function UserCard({ name, age }) {                          // same as: function UserCard(props)
      return <p>{name}, {age}</p>;                            //                { props.name }, { props.age }
  }




▸ The rules of props
      Read-only. A child must never change its props ( props.name = "x" throws an error — React freezes the
      props object in development). If something must change, it is state, owned by someone.
      One-way data flow. Data flows from parent to child only. When the parent re-renders with new values, the
      child re-renders with the new props.
      Any value. Text is written name="Asha" ; everything else goes in braces: numbers age={21} , booleans
      inStock={true} , arrays products={products} , objects product={p} , functions onAdd={addToCart} ,
      even JSX.


▸ Every way data moves between components

  Direction              How                                               ShopLite example

  Parent → child         Pass a prop                                        <ProductList products={visible} />

  Child → parent         Parent passes a function as a prop; the            <AddProductForm onAdd={addProduct} /> ,
                         child calls it with data                          form calls onAdd(form)

  Sibling ↔ sibling      Lift the state to the common parent, pass it       search lives in App, filters what ProductList gets
                         down to both (§4.9)

  Far-away               Context API (§4.13)                                useCart() in Header, ProductCard, Cart
  components

--- PDF page 247 ---
▸ More prop features you can mention

            children, default values and spreading


  // 1. children: whatever is written BETWEEN the opening and closing tags
  function Panel({ title, children }) {
       return (
        <section className="panel">
            <h3>{title}</h3>
            {children}
        </section>
       );
  }
  <Panel title="Cart"><p>Nothing here yet.</p></Panel>


  // 2. default value with a destructuring default
  function Badge({ label = "New" }) {
       return <span className="tag">{label}</span>;
  }
  <Badge />                            // shows "New"


  // 3. spread an object as props: same as name={p.name} price={p.price} ...
  <ProductCard key={p.id} {...p} />




   PYQ       Re-Exam 2023-24 · Q7(a)                                                                           10 M


  What are Props? Write a program to pass data from one component to another component using
  props.

   ✓    MODEL ANSWER — WRITE THIS


  1. DEFINITION

  Props (properties) are the inputs of a React component. A parent component passes data to a child com‐
  ponent as attributes in JSX, and the child receives them as a single object (its function parameter, usually
  destructured). Props let one component be reused with different data, just as a function is reused with dif‐
  ferent arguments.

  2. FEATURES OF PROPS

        Read-only (immutable) — the child cannot modify props.
        Unidirectional — data flows parent → child (top-down).
        Any type — strings, numbers, booleans, arrays, objects, functions, JSX ( children ).
        Re-render on change — when the parent passes new props, the child re-renders.
        Child → parent communication — the parent passes a callback function as a prop; the child calls it
        with data.

--- PDF page 248 ---
App (parent)     →         StudentList          →          StudentCard        ↺                Summary
               owns students state   props   students, onToggle     props     student, onToggle   onToggle(id)     total, present



  3. PROGRAM — ATTENDANCE APP (PARENT → CHILD, CHILD → PARENT, SIBLING VIA
  PARENT)

                   src/main.jsx


     import { createRoot } from "react-dom/client";
     import App from "./App.jsx";


     createRoot(document.getElementById("root")).render(<App />);



                   src/App.jsx — parent: owns the data and passes it down


     import { useState } from "react";
     import StudentList from "./components/StudentList.jsx";
     import Summary from "./components/Summary.jsx";


     const initialStudents = [
          { id: 1, name: "Asha", roll: 21, present: false },
          { id: 2, name: "Rahul", roll: 22, present: false },
          { id: 3, name: "Meera", roll: 23, present: false },
     ];


     export default function App() {
          const [students, setStudents] = useState(initialStudents);


          // passed DOWN as a prop; the child calls it to send the id UP
          function togglePresent(id) {
              setStudents((prev) =>
               prev.map((s) => (s.id === id ? { ...s, present: !s.present } : s))
              );
          }


          const presentCount = students.filter((s) => s.present).length;


          return (
              <div>
               <h1>Attendance — IMAP Lab</h1>
               <Summary total={students.length} present={presentCount} />
               <StudentList students={students} onToggle={togglePresent} />
              </div>
          );
     }

--- PDF page 249 ---
src/components/StudentList.jsx — receives an array, passes one item to each card


     import StudentCard from "./StudentCard.jsx";


     export default function StudentList({ students, onToggle }) {
         return (
           <ul>
              {students.map((s) => (
                <StudentCard key={s.id} student={s} onToggle={onToggle} />
              ))}
           </ul>
         );
     }



              src/components/StudentCard.jsx — reads props, calls the callback prop


     export default function StudentCard({ student, onToggle }) {
         const { id, name, roll, present } = student;
         return (
           <li>
              {roll} · {name} — {present ? "Present" : "Absent"}{" "}
              <button onClick={() => onToggle(id)}>
                Mark {present ? "absent" : "present"}
              </button>
           </li>
         );
     }



              src/components/Summary.jsx — a sibling that receives derived data


     export default function Summary({ total, present }) {
         return <p>Present: {present} / {total}</p>;
     }



              Output in the browser (after clicking "Mark present" for Asha)


     Attendance — IMAP Lab
     Present: 1 / 3
         • 21 · Asha — Present    [ Mark absent ]
         • 22 · Rahul — Absent    [ Mark present ]
         • 23 · Meera — Absent    [ Mark present ]



  4. HOW THE DATA TRAVELS

    1. App passes students and the function togglePresent to StudentList as props.

--- PDF page 250 ---
2. StudentList maps the array and passes one student object (with a unique key ) to each
         StudentCard .

    3. Clicking the button calls onToggle(id) — the child sends data up through the callback prop.
    4. App updates its state; React re-renders, and both StudentList and the sibling Summary receive the
        new props.

  Conclusion: props make components reusable and keep data flow predictable (one-way, top-down); call‐
  backs passed as props let children report events back to the parent that owns the state.

  🎯 Marking scheme guess: 2 M definition · 2 M features/diagram · 5 M working program (parent, child components, map + key, callback) ·
  1 M output/explanation




   PYQ       Final 2024-25 · Q7(b)                                                                                                 10 M


  What are props in React? Develop a simple React.js application that displays a list of your favourite
  movies using components and props.

   ✓    MODEL ANSWER — WRITE THIS


  1. WHAT ARE PROPS?

  Props (properties) are read-only inputs passed from a parent component to a child component, written like
  HTML attributes ( <MovieCard title="Inception" year={2010} /> ) and received by the child as an ob‐
  ject parameter. They make components reusable (one MovieCard component renders every movie) and
  enforce one-way data flow (parent → child). A child cannot change its props; any value can be passed —
  strings, numbers, arrays, objects, functions.

  2. COMPONENT DESIGN

                        App                     Header                   MovieList                   MovieCard × 5
               movies array (data)
                                      →     props: title, count
                                                                  +     props: movies
                                                                                        →      props: title, year, genre, rating



  3. PROJECT SETUP

              terminal


       npm create vite@latest movie-app -- --template react
       cd movie-app
       npm install
       npm run dev                   # open http://localhost:5173



  4. CODE

              src/main.jsx


       import { StrictMode } from "react";
       import { createRoot } from "react-dom/client";
       import App from "./App.jsx";

--- PDF page 251 ---
createRoot(document.getElementById("root")).render(
          <StrictMode>
           <App />
          </StrictMode>
     );



               src/App.jsx — parent: owns the data


     import Header from "./components/Header.jsx";
     import MovieList from "./components/MovieList.jsx";


     const movies = [
          { id: 1, title: "3 Idiots", year: 2009, genre: "Comedy-Drama", rating: 5 },
          { id: 2, title: "Inception", year: 2010, genre: "Sci-Fi", rating: 5 },
          { id: 3, title: "Interstellar", year: 2014, genre: "Sci-Fi", rating: 4 },
          { id: 4, title: "Dangal", year: 2016, genre: "Sports Drama", rating: 4 },
          { id: 5, title: "The Dark Knight", year: 2008, genre: "Action", rating: 5 },
     ];


     export default function App() {
          return (
           <div className="app">
               <Header title="My Favourite Movies" count={movies.length} />
               <MovieList movies={movies} />
           </div>
          );
     }



               src/components/Header.jsx


     export default function Header({ title, count }) {
          return (
           <header>
               <h1>{title}</h1>
               <p>{count} movies</p>
           </header>
          );
     }



               src/components/MovieList.jsx — receives the array, renders one card per movie


     import MovieCard from "./MovieCard.jsx";


     export default function MovieList({ movies }) {
          return (
           <ul className="movie-list">

--- PDF page 252 ---
{movies.map((m) => (
                <MovieCard
                    key={m.id}               // unique key for each list item
                    title={m.title}
                    year={m.year}
                    genre={m.genre}
                    rating={m.rating}
                />
              ))}
           </ul>
         );
     }



              src/components/MovieCard.jsx — reusable child, displays its props


     export default function MovieCard({ title, year, genre, rating = 3 }) {
         return (
           <li className="movie-card">
              <h3>{title} ({year})</h3>
              <p>Genre: {genre}</p>
              <p>My rating: {"★".repeat(rating)}</p>
           </li>
         );
     }



              Output in the browser


     My Favourite Movies
     5 movies
         • 3 Idiots (2009)              Genre: Comedy-Drama         My rating: ★★★★★
         • Inception (2010)             Genre: Sci-Fi               My rating: ★★★★★
         • Interstellar (2014)          Genre: Sci-Fi               My rating: ★★★★
         • Dangal (2016)                Genre: Sports Drama         My rating: ★★★★
         • The Dark Knight (2008)       Genre: Action               My rating: ★★★★★



  5. HOW PROPS ARE USED HERE

         App owns the movies array and passes it to MovieList as the prop movies , and title / count
         to Header .
         MovieList uses map() to create one MovieCard per movie, passing each field as a prop and a
         unique key .
         MovieCard is written once and reused five times; rating = 3 is a default prop value used if none is
         passed.
         Shortcut: <MovieCard key={m.id} {...m} /> spreads every field as a prop.

--- PDF page 253 ---
🎯 Marking scheme guess: 2 M props definition · 2 M component structure · 5 M code (App data, list with map + key, card with props) · 1
  M output




    4.6 State and useState
📚 Sources: Unit 4 Notes §5       LEC 9 (React) s.11   ShopLite React Manual 2.1, 2.2, 4.3   One-Shot p.13

 Complete Revision deck s.32


  🧠 START FROM ZERO
  Props come in from outside. State is data that a component owns and that changes over time — what
  the user typed, which tab is open, the list fetched from the server. A normal local variable is reset every time
  the function runs; state is remembered between renders, and changing it through its setter tells React to
  re-render.


             useState anatomy


  import { useState } from "react";


  const [count, setCount] = useState(0);
  //         │          │                        └─ initial value (used on the FIRST render only)
  //         │          └─ setter: call it to change the value and trigger a re-render
  //         └─ current value for THIS render


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



                                                                       3 · React re-renders
   1 · User clicks      →      2 · setCount(count + 1)      →       component function runs again
                                                                                                      →       4 · UI shows new count




▸ A controlled input — the search box (manual step 2.1)
A controlled input takes its value from state, and every keystroke updates that state through onChange .
React state is the single source of truth for what the box shows.

             src/App.jsx (manual step 2.1, excerpt)


  const [search, setSearch] = useState("");


  // derived value: computed from state on every render, NOT stored in state
  const visible = products.filter((p) =>
       p.name.toLowerCase().includes(search.toLowerCase())
  );

--- PDF page 254 ---
<input
       className="search"
       placeholder="Search products"
       value={search}                                                 // state -> input
       onChange={(e) => setSearch(e.target.value)}                    // input -> state
  />
  <ProductList products={visible} />


Type key and only the Mechanical Keyboard stays. Note that visible is not state: anything you can calculate from existing state or
props should be calculated during render, not stored twice.



▸ Never mutate state — make a new copy
React decides whether to re-render by comparing the old and new value with Object.is . If you change an ar‐
ray or object in place ( cart.push(p) ) and pass the same reference to the setter, React sees "nothing changed"
and the screen does not update. Always build a new array/object:

  Goal                  Wrong (mutates)                       Right (new copy)

  Add to array           cart.push(p);                        setCart([...cart, p])
                        setCart(cart)

  Remove from            cart.splice(i, 1)                    setCart(cart.filter(i => i.id !== id))
  array

  Update one item        cart[0].qty++                        setCart(cart.map(i => i.id === id ? { ...i, qty:
                                                              i.qty + 1 } : i))

  Update object          form.name = "x"                      setForm({ ...form, name: "x" })
  field

  Number                 count++                              setCount(count + 1)


The manual's AddProductForm (step 4.3) keeps one object in state and updates any field with one handler —
the input's name attribute picks the key:

           src/components/AddProductForm.jsx (excerpt)


  const emptyForm = { name: "", price: "", category: "" };
  const [form, setForm] = useState(emptyForm);


  function handleChange(e) {
       setForm({ ...form, [e.target.name]: e.target.value });                    // copy, then overwrite one key
  }


  <input name="price" type="number" value={form.price} onChange={handleChange} />

--- PDF page 255 ---
🔑 FIVE FACTS ABOUT USESTATE
    1. Returns a pair [value, setter] ; the argument is the initial value (a function
        useState(() => load()) is called only once — "lazy initial state").

    2. State is local and private: two <Counter /> s each have their own count .
    3. The setter replaces the value (unlike a class's setState , which merges).
    4. Setting the same value ( Object.is equal) skips the re-render.
    5. The new value is visible on the next render, not on the next line (§4.8).




    4.7 Props vs state
📚 Sources: Unit 4 Notes §6       LEC 9 (React) s.12   ShopLite React Manual 2.1   One-Shot p.13     Complete Revision deck s.32


  Feature                   Props                                                 State

  Owned by                  The parent component                                  The component itself

  Can change?               No — read-only inside the child                       Yes — through the setter

  Purpose                   Configure a component from outside                    Remember data that changes over time

  Triggers re-render        When the parent passes new props                      When the setter is called with a new value

  Set by                    JSX attributes: <Card title="HTML" />                  useState(initial) , then setX(...)

  Analogy                   Function arguments                                    Variables that remember

  ShopLite                   products given to ProductList                         search in App



  💡 THINK OF IT LIKE
  A question paper is handed to you by the invigilator — you can read it but you may not change it: that is
  props. Your answer sheet is yours, and it keeps changing as you write: that is state. And what you write on
  your sheet can later be handed to someone else (the evaluator) — one component's state very often be‐
  comes another component's props.



   PYQ       Final 2025-26 · Q1(a)   ★ LATEST                                                                                     4M


  Props vs State — define each and give one classroom example for both (no code run needed). When
  would you use props vs state in a component?

   ✓   MODEL ANSWER — WRITE THIS

  Props are read-only inputs passed from a parent component to a child component (like function
  arguments). The child can use them but cannot change them; data flows one way, parent → child.
  State is data owned and managed inside a component that can change over time (created with
    useState ); calling its setter re-renders the component.

--- PDF page 256 ---
Classroom example. A ClassRoom parent renders one StudentCard per student and passes
    name="Asha" and rollNo={21} — these are props: the card displays them but never edits them. Inside
  each card, an "attendance" toggle keeps const [present, setPresent] = useState(false) — this is
  state, because it changes when the teacher clicks "Mark present".

              sketch


     <StudentCard name="Asha" rollNo={21} />                             // props from the parent


     function StudentCard({ name, rollNo }) {
         const [present, setPresent] = useState(false); // state owned by the card
         return (
           <button onClick={() => setPresent(!present)}>
              {rollNo} {name}: {present ? "Present" : "Absent"}
           </button>
         );
     }



  When to use which: use props for data that comes from outside and only configures how a component
  looks or behaves (titles, items to display, callback functions). Use state for data that changes during the
  component's life because of user actions, timers or API responses, and that this component is responsible
  for. If two components need the same changing data, keep it as state in their common parent and pass it
  down as props.

  🎯 Marking scheme guess: 1 M props definition · 1 M state definition · 1 M classroom example · 1 M when to use


    4.8 State updates: snapshots, batching, functional updates
📚 Sources: Unit 4 Notes §5 (only "never change state directly")
 Not in your files — added from standard references (react.dev: "State as a Snapshot", "Queueing a Series of State Updates")


     🚨 NOT IN YOUR STUDY MATERIAL · 8 MARKS · FINAL 2025-26 Q2(A)
     Gap G3. The latest paper asks why setState does not update immediately, what batching is, when up‐
     dates actually apply, and when to use functional updates prev => … with two critical scenarios. Your
     notes only say "never change state directly" — batching, snapshots and updater functions appear in
     none of your files.

     Verdict: MUST LEARN. It is 8 marks in the newest paper, it explains real bugs you will meet (stale coun‐
     ters, timers stuck at 1) and it makes your answers on useEffect (Q1b, Q2B) sharper. Learn the three ideas
     below: snapshot → batching → updater functions.

--- PDF page 257 ---
▸ Idea 1 — state is a snapshot
Each render is a function call. During that call, count is just a constant holding that render's value. Calling
 setCount does not change the variable you already have; it asks React for a new render in which
 useState will return the new value.

            the "it didn't update!" surprise


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


      function handleClick() {
          setCount(count + 1);
          console.log(count);          // prints 0, not 1 — this render's snapshot
          setTimeout(() => alert(count), 3000);      // still 0 three seconds later
      }
      return <button onClick={handleClick}>{count}</button>;          // shows 1 after re-render
  }




▸ Idea 2 — React batches state updates

  💡 THINK OF IT LIKE
  A waiter does not run to the kitchen after you name each dish. They wait until the whole table has ordered,
  then take one trip. React does the same: it collects every setX call made while your event handler runs
  and then does one re-render.


Batching means grouping several state updates into a single re-render. Why React does it:

      Performance — three updates in one click cause one render and one DOM commit, not three.
      Consistency — the user never sees a half-updated screen (e.g. loading already false but data still
      empty).
      Predictability — every render works with one consistent snapshot of all state values.

React 18 automatic batching. Before React 18, updates were batched only inside React event handlers; up‐
dates inside setTimeout , promises or fetch().then() each caused a separate render. Since React 18 (with
 createRoot , which Vite and ShopLite use) all updates are batched automatically — in event handlers, time‐
outs, promises, async functions and native listeners .

            one render, not three — even after an await (React 18+)


  async function load() {
      const res = await api.get("/products/");
      setProducts(res.data);        // queued
      setError("");                 // queued
      setLoading(false);            // queued -> ONE re-render after this code finishes
  }

--- PDF page 258 ---
// rare opt-out: force React to apply an update immediately
  import { flushSync } from "react-dom";
  flushSync(() => setCount((c) => c + 1));          // DOM is updated when this line returns




▸ When do the updates actually apply?

 1        Your handler runs. Each setX(…) only adds an entry to that state's update queue. Variables in the
          running code keep their old (snapshot) values.

 2        The handler finishes. React waits until all code in the event handler (or the current task/microtask) has
          completed.

 3        React re-renders. It calls your component again; inside it, useState processes the queue in order
          and returns the final value.

 4        Commit and effects. React updates the DOM, the browser paints, then effects that depend on the
          changed state run — that is the first place your code can "see" the new value.


▸ Idea 3 — functional (updater) updates
Instead of a value, you can pass the setter a function: setCount(prev => prev + 1) . React puts the function
in the queue and, during the next render, calls it with the latest pending state — the result of all earlier updates
in the queue — not the stale snapshot.

           count starts at 0 — value form vs updater form


  function addThreeWrong() {
      setCount(count + 1);          // snapshot 0 + 1 -> "replace with 1"
      setCount(count + 1);          // snapshot 0 + 1 -> "replace with 1"
      setCount(count + 1);          // snapshot 0 + 1 -> "replace with 1"
  }                                 // next render: count = 1


  function addThreeRight() {
      setCount((c) => c + 1);       // 0 -> 1
      setCount((c) => c + 1);       // 1 -> 2   (receives the previous updater's result)
      setCount((c) => c + 1);       // 2 -> 3
  }                                 // next render: count = 3



How React processes a mixed queue (number = 0):

 Queued update                                  Meaning                                          Value after it

  setNumber(number + 5)                         "replace with 5" (snapshot 0 + 5)                5

  setNumber(n => n + 1)                         updater: 5 + 1                                   6

  setNumber(42)                                 "replace with 42"                                42 ← final

--- PDF page 259 ---
▸ When functional updates are critical — five scenarios

1 · SEVERAL UPDATES TO THE SAME STATE IN ONE HANDLER
Shown above: +1 three times needs c => c + 1 , otherwise you get +1.

2 · TIMERS AND INTERVALS (STALE CLOSURE)

           a clock stuck at 1


  useEffect(() => {
      const id = setInterval(() => {
        // BUG: this closure captured seconds = 0 forever, so it always sets 1
        setSeconds(seconds + 1);
      }, 1000);
      return () => clearInterval(id);
  }, []);


  // FIX: the updater always gets the latest value, so [] is fine
  const id = setInterval(() => setSeconds((s) => s + 1), 1000);



A closure is a function that remembers the variables of the render it was created in. The interval callback was
created in the first render, so it sees seconds = 0 forever. The updater form never reads the captured variable.

3 · ASYNC CALLBACKS — THE VALUE CHANGED WHILE YOU WERE WAITING

           like button, clicked twice quickly


  async function handleLike() {
      await api.post(`/posts/${id}/like/`);      // takes ~500 ms
      setLikes(likes + 1);         // BUG: both clicks captured likes = 10 -> ends at 11
      setLikes((l) => l + 1);      // FIX: 10 -> 11 -> 12
  }



4 · RAPID TOGGLES
With open = false , calling setOpen(!open) twice in the same batch (a fast double click, or a handler plus a
keyboard shortcut) queues "replace with true " twice — both read the snapshot false — so a double toggle
wrongly ends at true . setOpen(o => !o) twice gives false → true → false , as intended.

5 · LIST UPDATES FROM ASYNC RESULTS

           adding items as they arrive


  // two uploads finish close together; with [...items, x] the second overwrites the first
  socket.onmessage = (e) => setMessages((prev) => [...prev, JSON.parse(e.data)]);


  async function addProduct(data) {
      const res = await api.post("/products/", data);

--- PDF page 260 ---
setProducts((prev) => [...prev, res.data]);            // safe even if the list changed meanwhile
  }



  ✍️ RULE OF THUMB FOR THE EXAM
   If the new state is computed from the previous state, use the updater form. If you are simply replacing it
  with an unrelated value ( setSearch(e.target.value) , setProducts(res.data) ), the value form is fine.
  Updaters must be pure (no side effects) — in StrictMode React calls them twice in development to check.


  ⚠️ "BUT I NEED THE NEW VALUE RIGHT NOW"
  Compute it into a variable first and use that:
    const next = count + 1; setCount(next); api.post("/count/", { value: next }); . Or react to the
  change after render with useEffect(() => { … }, [count]) . Never "wait" for count to change on the
  next line — it will not.



   PYQ       Final 2025-26 · Q2(A)   ★ LATEST                                                                           8M


  A student's state update doesn't reflect immediately after setState. Explain why React batches state
  updates and when they actually apply. Explain when to use functional updates (prevState => ...) and
  give two scenarios where functional updates are critical.

   ✓    MODEL ANSWER — WRITE THIS


  WHY THE UPDATE IS NOT IMMEDIATE

  In React, state behaves like a snapshot. When a component renders, count is a constant for that render.
  Calling setCount(count + 1) does not modify that variable; it queues an update and schedules a re-
  render. So code on the next line (e.g. console.log(count) ) still sees the old value. The new value only
  exists in the next render, when useState returns it.

  WHY REACT BATCHES UPDATES

  Batching = React groups multiple state updates made during one event into a single re-render. Reasons:
  (1) performance — one render and one DOM commit instead of many; (2) consistency — the UI never
  shows a half-updated state such as loading=false while data is still empty; (3) every render works from
  one coherent snapshot. Since React 18 automatic batching, this happens everywhere — event handlers,
    setTimeout , promises, async/await code — not only in React event handlers. ( flushSync can force
  an immediate update in rare cases.)

  WHEN UPDATES ACTUALLY APPLY

             Handler runs                                              Re-render
           setX calls are queued
                                     →     Handler ends   →     queue processed in order
                                                                                           →    Commit + paint        →

                                                    useEffect sees new value

--- PDF page 261 ---
FUNCTIONAL UPDATES

  A functional (updater) update passes a function: setCount(prev => prev + 1) . React calls it with the lat‐
  est pending state (after all earlier queued updates), not the stale snapshot. Use it whenever the next
  state depends on the previous state.

              value form vs updater form


     // count = 0
     setCount(count + 1); setCount(count + 1); setCount(count + 1);                        // -> 1 (all read 0)
     setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); // -> 3 (chained)



  TWO CRITICAL SCENARIOS

  1. Timers / intervals (stale closure). An interval created on mount captures the first render's value, so
    setSeconds(seconds + 1) sets 1 forever. setSeconds(s => s + 1) always increments the latest value.

              scenario 1


     useEffect(() => {
         const id = setInterval(() => setSeconds((s) => s + 1), 1000);
         return () => clearInterval(id);
     }, []);



  2. Async callbacks and rapid clicks. When a user clicks "Like" twice quickly and the update happens af‐
  ter an await , both callbacks captured the same old likes value; setLikes(likes + 1) loses one
  click, while setLikes(l => l + 1) counts both. The same applies to toggles ( setOpen(o => !o) ) and
  adding to lists from async results ( setItems(prev => [...prev, newItem]) ).

              scenario 2


     async function handleLike() {
         await api.post(`/posts/${id}/like/`);
         setLikes((l) => l + 1);                // correct even for rapid double clicks
     }



  Conclusion: React treats state as a snapshot and batches updates for speed and consistency; updates
  apply on the next render. When the new state is derived from the old one — especially in timers, async
  code, repeated updates, toggles and list changes — use the functional form.

  🎯 Marking scheme guess: 2 M snapshot + why not immediate · 2 M batching reasons (incl. React 18) · 1 M when updates apply · 1 M
  functional update explained · 2 M two scenarios with code




   ✏️ PREDICT THE OUTPUT — WHAT IS SHOWN AFT ER ONE CL ICK ?
   Each handler starts with count = 0 and runs on one button click.

              five handlers

--- PDF page 262 ---
// (a)
     setCount(count + 1); setCount(count + 1);
     // (b)
     setCount(c => c + 1); setCount(c => c + 1);
     // (c)
     setCount(count + 5); setCount(c => c + 1);
     // (d)
     setCount(c => c + 1); setCount(10);
     // (e)
     setCount(count + 1); console.log(count);                       // what is logged?



    1. (a) shows                     (b) shows                     (c) shows                    (d) shows
    2. (e) logs                   and the button then shows
    3. How many re-renders does each handler cause in React 18?

   🔓 Answer key: (a) 1 · (b) 2 · (c) 6 · (d) 10 · (e) logs 0, shows 1 (snapshot) · one re-render each (batching).


    4.9 Lifting state up
📚 Sources: Unit 4 Notes §5.1        LEC 9 (React) s.12     ShopLite React Manual 2.1, 2.2       One-Shot p.13       Complete Revision deck s.32


Lifting state up means: when two or more components need the same changing data, remove the state from
the individual components and move it to their closest common parent. The parent passes the value down as
props, and passes functions down so children can request changes.


                                                                     Parent
                                                      owns the state (single source of truth)
                event goes UP via callback
                                         props: value, onChange ↓                                 props: value ↓



                                 Child A                                                                Child B
                        calls onChange(newValue)                                                     displays value


                                                  State down as props, events up as callbacks.



▸ Why it is needed
    State is private to a component; a sibling cannot read it. If each child kept its own copy, the copies could
    drift out of sync.
    Data in React flows only downward, so shared data must live above everyone who needs it.
    It gives a single source of truth: one owner, one place to update, consistent UI.

--- PDF page 263 ---
▸ Example — search box and list as siblings

            before and after lifting


  // BEFORE: SearchBar owns query -> sibling StudentList cannot see it to filter
  function SearchBar() {
       const [query, setQuery] = useState("");
       return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
  }


  // AFTER: SearchBar is "controlled" by its parent: no state of its own
  function SearchBar({ value, onChange }) {
       return <input value={value} onChange={(e) => onChange(e.target.value)} />;
  }



 App now holds const [query, setQuery] = useState("") , passes value={query} onChange={setQuery}
to SearchBar and the filtered names to the sibling StudentList — full code in the model answer below.

ShopLite does exactly this: search lives in App (not in the input) because App also needs it to filter what it
hands to ProductList ; and in step 2.2 the cart state lives in App so the header badge and the Add buttons
share one cart.


▸ Alternatives when lifting is not enough

  Approach                                When

  Context API (+ useReducer )             Many components at different depths need the data; avoids prop drilling (§4.13–4.14,
                                          ShopLite's CartProvider )

  State library (Redux Toolkit,           Large app-wide state with many updates, devtools, middleware
  Zustand)

  Server-state cache (TanStack            The shared data is really server data (lists fetched from Django)
  Query)

  URL state (query string / route         Filters, search terms, page numbers that should survive a reload or be shareable
  params)



   PYQ       Final 2025-26 · Q2(C)   ★ LATEST                                                                                 6M


  Explain "lifting state up" in React. Why is it needed? Give a practical example of lifting state from
  child to parent. Mention one alternative approach to sharing state between components.

   ✓    MODEL ANSWER — WRITE THIS

  Lifting state up is the React pattern of moving state out of a child component into the closest common
  parent of all components that need it. The parent becomes the single owner (single source of truth); it
  passes the value down as props and passes a callback function down so children can ask for changes.

--- PDF page 264 ---
Why needed: (1) state is private to a component, so siblings cannot read each other's state; (2) React data
  flows only parent → child, so shared data must live above all users; (3) keeping one copy prevents compo‐
  nents from going out of sync.

  Example. A SearchBar kept query in its own state, so the sibling StudentList could not filter by it. We
  lift query to App :

                App.jsx (parent) + children


     function App() {
         const [query, setQuery] = useState("");                                       // lifted state
         const names = ["Asha", "Rahul", "Meera"];
         const visible = names.filter((n) => n.toLowerCase().includes(query.toLowerCase()));
         return (
           <>
              {/* down: value + callback */}
              <SearchBar value={query} onChange={setQuery} />
              {/* the sibling uses the lifted state */}
              <StudentList names={visible} />
           </>
         );
     }


     function SearchBar({ value, onChange }) {                                       // child: no own state
         return <input value={value} onChange={(e) => onChange(e.target.value)} />;
     }


     function StudentList({ names }) {
         return <ul>{names.map((n) => <li key={n}>{n}</li>)}</ul>;
     }



  Typing in SearchBar calls onChange → setQuery in App → App re-renders → StudentList receives
  the filtered names. (Same as ShopLite, where search lives in App to filter ProductList .)

  Alternative: the Context API — create a context with createContext() , hold the state in a Provider com‐
  ponent (optionally with useReducer ), wrap the tree, and read it anywhere with useContext() . This avoids
  prop drilling when the components are far apart (e.g. ShopLite's CartProvider + useCart() ). Libraries
  such as Redux Toolkit or Zustand are another option for large apps.

  🎯 Marking scheme guess: 1 M definition · 1 M why needed · 3 M example with code + flow · 1 M alternative


    4.10 Hooks and the rules of hooks
📚 Sources: Unit 4 Notes §7      LEC 9 (React) s.13   ShopLite React Manual 2–3     One-Shot p.14     Complete Revision deck s.33


Hooks are special functions, all named use… , that let function components "hook into" React features that
used to need classes: state, side effects/lifecycle, context, refs. They arrived in React 16.8 (2019).

--- PDF page 265 ---
Where in this
  Hook                         What it does                                 Typical use
                                                                                                                chapter

   useState                    Remember data between renders                Counters, form inputs               §4.6, §4.8

   useEffect                   Run side effects after render                Fetch data, timers, documen‐        §4.11
                                                                            t.title

   useRef                      Hold a value or DOM node without re-         Focus an input, store a timer id    below
                               rendering

   useMemo / use‐              Cache a calculated result / a function be‐   Skip heavy recalculation; sta‐      §4.11
  Callback                     tween renders                                ble deps

   useContext                  Read shared (context) data                   Theme, logged-in user, cart         §4.13

   useReducer                  Manage complex state with actions            Cart, multi-field forms             §4.14

  Custom hook                  Your own reusable logic (name starts with     useCart , useFetch ,               §4.13, §4.15
                                use )                                        useAuth


              useRef — focus an input without any state


  import { useRef } from "react";


  function SearchFocus() {
      const inputRef = useRef(null);                           // { current: null }, survives re-renders
      return (
         <>
           <input ref={inputRef} placeholder="Search" />
           <button onClick={() => inputRef.current.focus()}>Focus search</button>
         </>
      );
  }


Changing ref.current does not re-render — that is the difference from state. Newer hooks you may meet: useId ,
 useTransition (React 18); use , useActionState , useOptimistic (React 19). Knowing the names is enough.


▸ The two rules of hooks
 1. Call hooks only at the top level of a component — never inside if , loops, nested functions or after an
      early return .
 2. Call hooks only from React function components or custom hooks — not from ordinary JavaScript func‐
      tions or class components.

              wrong vs right


  // WRONG: the hook is skipped on renders where loggedIn is false
  function Profile({ loggedIn }) {
      if (loggedIn) {
         const [name, setName] = useState("");

--- PDF page 266 ---
}
      const [age, setAge] = useState(0);                 // shifts into the wrong slot
  }


  // RIGHT: hooks first, conditions after
  function Profile({ loggedIn }) {
      const [name, setName] = useState("");
      const [age, setAge] = useState(0);
      if (!loggedIn) return <Login />;
      // ... use name and age
  }



  🧠 WHY THE RULES EXIST
  React does not know your state by name — it matches hooks by call order: "first useState call = slot 1,
  second = slot 2…". If a hook is skipped on one render (inside a false if ), every hook after it shifts by one
  slot and reads the wrong state. Keeping hooks at the top level guarantees the same order on every render.




      4.11 useEffect in depth
📚 Sources: Unit 4 Notes §8       LEC 9 (React) s.14     ShopLite React Manual 2.3, 4.2   One-Shot p.14     Complete Revision deck s.33

 Race conditions & dependency pitfalls: added from standard references


A component's job is to compute JSX. Anything that reaches outside the component — fetching data, starting
a timer, subscribing to a socket, changing document.title , touching the DOM directly — is a side effect.
 useEffect runs that code after React has committed the render to the screen, so it never blocks drawing
the UI.

            signature


  useEffect(() => {
      // setup: the side effect
      return () => {
          // optional cleanup: undo the effect
      };
  }, [dep1, dep2]);           // optional dependency array



  Code                      Runs when                                         Use for

   useEffect(fn)            After every render                                Rarely right — logging, syncing with something that
                                                                              changes every render

   useEffect(fn,            Once, after the first render (cleanup on          Initial fetch, start a timer/subscription
  [])                       unmount)

--- PDF page 267 ---
Code                         Runs when                                      Use for

   useEffect(fn,               After the first render, and again whenever     Re-fetch when a prop/state changes, sync the title
  [id])                         id changes



▸ The effect lifecycle

                              Mount                                   Update                             Unmount
                        render → effect runs
                                               →     deps changed → cleanup (old) → effect (new)
                                                                                                   →    cleanup runs



Cleanup runs before every re-run of the effect (to undo the previous one) and when the component is re‐
moved. In development, <StrictMode> deliberately runs mount → cleanup → mount once more to prove your
cleanup works — that is why ShopLite's Network tab shows two products/ requests in development.


▸ The three classic examples

           1 · after the first render only — initial fetch (ShopLite step 4.2)


  useEffect(() => {
     load();                                       // api.get("/products/") -> setProducts(...)
  }, []);                                          // empty array: run once on mount



           2 · after a particular state changes — tab title follows the cart (ShopLite step 3.2)


  useEffect(() => {
     document.title = count > 0 ? `(${count}) ShopLite` : "ShopLite";
  }, [count]);                                     // first render + every time count changes



           3 · cleanup on unmount — stop a timer (Unit 4 Notes §8.1)


  useEffect(() => {
     const t = setInterval(tick, 1000);                    // start
     return () => clearInterval(t);                        // stop when the component goes away
  }, []);




▸ The dependency array — what it really does
    After each render React compares every value in the array with its value from the previous render using
     Object.is . If any changed, it runs the cleanup and then the effect again; if none changed, it skips the
    effect.
    It must list every reactive value the effect reads: props, state, and variables/functions declared inside the
    component. The ESLint rule react-hooks/exhaustive-deps (on by default in Vite's template) warns when
    one is missing.
    Omitted entirely → the effect runs after every render. If such an effect calls a setter that changes state, it
    causes another render, which runs the effect again — an infinite loop.

--- PDF page 268 ---
[] → nothing to compare, so it runs only after mount (and cleans up on unmount).


  ⚠️ THE EFFECT FUNCTION ITSELF CANNOT BE ASYNC
    useEffect(async () => { … }) is wrong: an async function returns a Promise, but React expects either
  nothing or a cleanup function. Define an async function inside and call it (Unit 4 Notes §12):
    useEffect(() => { async function load() { … } load(); }, []);



▸ Race conditions — when responses arrive out of order
If query changes from "re" to "react", two requests are in flight. If the "re" response arrives last, it overwrites
the correct results. The cleanup function fixes this: it runs before the next effect, so it can mark the old request
as stale or cancel it.

           fix 1 — ignore flag


  useEffect(() => {
     let ignore = false;
     async function load() {
         const res = await api.get("/products/", { params: { search: query } });
         if (!ignore) setResults(res.data);          // only the latest effect may set state
     }
     load();
     return () => { ignore = true; };                // runs when query changes or on unmount
  }, [query]);



Fix 2 — AbortController actually cancels the old HTTP request: create new AbortController() in the ef‐
fect, pass { signal: controller.signal } to fetch/axios, and return () => controller.abort() (code in
the Q2(B) answer below).


▸ Dependency bugs and their fixes

  Bug                                     Symptom                                        Fix

  Missing dependency                      Stale data: the effect keeps using the first   Add it to the array
                                          render's value (manual step 2.3: change
                                           [cart] to [] and the title never
                                          updates)

  Object/array/function created during    New reference every render → effect runs       Depend on primitives ( q ), create
  render in the array ( const opts = {    every render → request storm / loop            the object inside the effect, or
  q } )                                                                                  wrap with useMemo / useCall‐
                                                                                         back

  Effect sets the state it depends on     Infinite loop: fetch → set → render →          Remove it from deps; use a func‐
  ( [results] + setResults(new            fetch …                                        tional update setX(prev =>
  array) )                                                                               …) if you need the old value

--- PDF page 269 ---
Bug                                            Symptom                                           Fix

  Unrelated dependencies                         Effect re-runs when it does not need to:          Keep only what the effect reads;
                                                 wasted API calls, flicker, races                  split unrelated work into separate
                                                                                                   effects



   PYQ       Final 2025-26 · Q1(b)   ★ LATEST                                                                                   5M


  When does useEffect run? Give an example each for: after first render; after a particular state
  changes; cleanup on unmount. What is the role of the dependency array and what happens if you
  omit it entirely?

   ✓    MODEL ANSWER — WRITE THIS

    useEffect(setup, deps) runs its setup function after React has rendered the component and committed
  the changes to the DOM (it never runs during render). When it re-runs is controlled by the dependency ar‐
  ray; the optional function it returns is the cleanup, which runs before the next re-run and when the compo‐
  nent unmounts.

              the three examples


       // (1) after the first render only
       useEffect(() => {
         fetch("/api/products/").then((r) => r.json()).then(setProducts);
       }, []);


       // (2) after a particular state (count) changes — also runs on first render
       useEffect(() => {
         document.title = `Cart (${count})`;
       }, [count]);


       // (3) cleanup on unmount
       useEffect(() => {
         const id = setInterval(() => setSeconds((s) => s + 1), 1000);
         return () => clearInterval(id);                   // runs when the component is removed
       }, []);



  Role of the dependency array: it lists the values (props/state) the effect uses. After every render React
  compares each value with the previous render ( Object.is ); the effect re-runs only if one has changed.
    [] means "run once after mount"; [count] means "run on mount and whenever count changes".
  Listing every value the effect reads prevents stale data.

  If omitted entirely ( useEffect(fn) ), the effect runs after every render — the first and every update. This
  is wasteful for fetches, and if the effect sets state it triggers another render, causing an infinite loop.

  🎯 Marking scheme guess: 1 M when it runs · 2 M three examples · 1 M role of dependency array · 1 M omitting it

--- PDF page 270 ---
PYQ         Final 2025-26 · Q2(B)   ★ LATEST                                                                       6M


  A component fetches data in useEffect but forgets to include `query` in the dependencies. What bug
  can occur? How do you fix it? What happens if you include too many or wrong dependencies?

   ✓       MODEL ANSWER — WRITE THIS

                buggy code


       function SearchResults({ query }) {
           const [results, setResults] = useState([]);


           useEffect(() => {
              fetch(`/api/products/?search=${query}`)
                .then((res) => res.json())
                .then((data) => setResults(data));
           }, []);                                // BUG: query is used but not listed


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



  THE BUG

  With [] the effect runs only once, after the first render, using the first value of query (captured in a clo‐
  sure). When the user types a new search term, query changes but the effect does not re-run, so no new
  request is sent and the list shows stale results that do not match the input. This is a stale closure bug;
  there is no error message, which makes it hard to notice.

  THE FIX
  Add query to the dependency array so the effect re-runs whenever it changes, and add a cleanup so an
  older, slower response cannot overwrite a newer one (race condition):

                fixed


       useEffect(() => {
           const controller = new AbortController();
           const url = `/api/products/?search=${encodeURIComponent(query)}`;
           fetch(url, { signal: controller.signal })
              .then((res) => res.json())
              .then((data) => setResults(data))
              .catch((err) => { if (err.name !== "AbortError") console.error(err); });
           return () => controller.abort();            // cancel the previous request
       }, [query]);                                   // re-run whenever query changes



  TOO MANY OR WRONG DEPENDENCIES

           Unstable values (an object, array or function created during render, e.g.
           const options = { search: query } ) get a new reference every render, so the effect runs after every

--- PDF page 271 ---
render — repeated API calls, and an infinite loop if the effect also sets state.
       State the effect itself sets (e.g. [results] while calling setResults ) → fetch → set → render →
       fetch … endlessly.
       Unrelated dependencies → the effect re-runs when nothing it uses changed: wasted network re‐
       quests, flickering loaders and more race conditions.

  Good practice: list exactly the values the effect reads (the exhaustive-deps lint rule checks this), prefer
  primitive dependencies, move objects/functions inside the effect or stabilise them with
    useMemo / useCallback , and use functional updates ( setX(prev => …) ) to avoid depending on state.


  🎯 Marking scheme guess: 2 M bug (stale results / closure) · 2 M fix with [query] (+ cleanup) · 2 M too many / wrong deps

   ✏️ WHEN DOES IT RUN? FILL IN THE DEP ENDE NCY ARR AY
    1. Log "mounted" once when the component appears:
        useEffect(() => console.log("mounted"),                                    );

    2. Re-fetch the student whenever the prop studentId changes:
        useEffect(() => { load(studentId); },                                 );

    3. Run after every single render: useEffect(() => { … }                                );

    4. Stop the timer on unmount:
        useEffect(() => { const id = setInterval(tick, 1000);                                           }, []);

    5. Which lifecycle method does item 4's cleanup replace?

   🔓 Answer key: 1) [] 2) [studentId] 3) leave the array out completely 4) return () => clearInterval(id); 5)
   componentWillUnmount




    4.12 Hook programs: counter apps for the exam
📚 Sources: Unit 4 Notes §5, §7, §8      LEC 9 (React) s.11, s.13–14    ShopLite React Manual 2.1–2.3


Two papers asked you to write a hooks program. Learn one compact demo (5 marks) and one multi-component
counter app (10 marks). Both reuse what you already know: useState , functional updates, useEffect with
cleanup, props.


   PYQ       Re-Exam 2023-24 · Q1(c)                                                                                                5M


  Write a short program to demonstrate React Hooks.

   ✓   MODEL ANSWER — WRITE THIS

  Hooks are functions starting with use that let function components use React features: useState adds
  state, useEffect runs side effects after render, useRef keeps a value or DOM reference without re-ren‐
  dering. The program below uses all three.

              src/HooksDemo.jsx

--- PDF page 272 ---
import { useState, useEffect, useRef } from "react";


     export default function HooksDemo() {
         const [count, setCount] = useState(0);                      // useState: a counter
         const [seconds, setSeconds] = useState(0);                  // useState: a timer value
         const inputRef = useRef(null);                              // useRef: a DOM element


         useEffect(() => {                                           // useEffect with a dependency
           document.title = `Clicked ${count} times`;
         }, [count]);


         useEffect(() => {                                           // useEffect once + cleanup
           const id = setInterval(() => setSeconds((s) => s + 1), 1000);
           return () => clearInterval(id);
         }, []);


         return (
           <div>
              <h2>React Hooks Demo</h2>
              <p>You clicked {count} times · on page for {seconds}s</p>
              <button onClick={() => setCount((c) => c + 1)}>Click me</button>
              <input ref={inputRef} placeholder="Your name" />
              <button onClick={() => inputRef.current.focus()}>Focus input</button>
           </div>
         );
     }



               src/main.jsx


     import { createRoot } from "react-dom/client";
     import HooksDemo from "./HooksDemo.jsx";


     createRoot(document.getElementById("root")).render(<HooksDemo />);



  Output: "You clicked 0 times · on page for 0s"; the seconds count up every second; each click increases
  the count and the browser tab title changes to "Clicked 3 times"; "Focus input" puts the cursor in the text
  box. When the component is removed, the cleanup stops the interval.

  🎯 Marking scheme guess: 1 M what hooks are · 3 M program (useState, useEffect + cleanup, useRef) · 1 M explanation/output

   PYQ        Final 2024-25 · Q5(b)                                                                                           10 M


  What is the difference between state and hooks in React? Build a React app implementing compo‐

--- PDF page 273 ---
nents that utilize state and hooks through a counter program.

   ✓     MODEL ANSWER — WRITE THIS


  1. STATE

  State is data that a component owns and that changes over time (a count, form input, fetched list). When
  state changes, React re-renders the component so the UI matches the data. State exists in both class com‐
  ponents ( this.state ) and function components.

  2. HOOKS

  Hooks are special functions (introduced in React 16.8) whose names start with use ; they let function
  components use React features such as state ( useState ), side effects ( useEffect ), context
  ( useContext ), refs ( useRef ) and reducers ( useReducer ). Rules: call them only at the top level, and only
  inside components or custom hooks.

  3. DIFFERENCE

    Point        State                                                     Hooks

    What it      The data a component remembers                            The functions/API that give function components features
    is

    Purpose      Store changing values that drive the UI                   Add state, effects, context, refs, reducers to functions

    Where        Class ( this.state ) and function                         Only function components and custom hooks
                 components

    Relation     Created in a function component by the hook                useState is one hook; others ( useEffect , useRef ) are
                  useState                                                 not about state

    Update       Through the setter / setState → re-render                 Follow the rules of hooks (top level, same order)

    Example       count = 5                                                 const [count, setCount] = useState(0)


  4. COUNTER APP — COMPONENT DESIGN

                                    App                            CounterDisplay                    StepSelector
                        state: count, step · useEffect
                                                            →         props: count
                                                                                         +     props: step, onStepChange
                                                                                                                               +

                                                                   CounterControls
                                                         props: onIncrement, onDecrement, onReset



               src/main.jsx


       import { StrictMode } from "react";
       import { createRoot } from "react-dom/client";
       import App from "./App.jsx";


       createRoot(document.getElementById("root")).render(
         <StrictMode>
            <App />

--- PDF page 274 ---
</StrictMode>
     );



               src/App.jsx — owns the state, uses useState and useEffect


     import { useState, useEffect } from "react";
     import CounterDisplay from "./components/CounterDisplay.jsx";
     import CounterControls from "./components/CounterControls.jsx";
     import StepSelector from "./components/StepSelector.jsx";


     export default function App() {
          const [count, setCount] = useState(0);       // hook #1: the counter value
          const [step, setStep] = useState(1);         // hook #2: how much to add


          // hook #3: side effect after render — runs whenever count changes
          useEffect(() => {
           document.title = `Count: ${count}`;
          }, [count]);


          // functional updates: correct even with fast repeated clicks
          const increment = () => setCount((c) => c + step);
          const decrement = () => setCount((c) => Math.max(0, c - step));      // never below 0
          const reset = () => setCount(0);


          return (
           <div className="app">
               <h1>Counter App</h1>
               <CounterDisplay count={count} />
               <StepSelector step={step} onStepChange={setStep} />
               <CounterControls
                onIncrement={increment}
                onDecrement={decrement}
                onReset={reset}
               />
           </div>
          );
     }



               src/components/CounterDisplay.jsx


     export default function CounterDisplay({ count }) {
          return (
           <h2 style={{ color: count >= 10 ? "green" : "black" }}>
               Current count: {count}
           </h2>

--- PDF page 275 ---
);
     }



                 src/components/StepSelector.jsx — controlled input


     export default function StepSelector({ step, onStepChange }) {
         return (
            <label>
              Step:{" "}
              <input
                  type="number"
                  min="1"
                  value={step}
                  onChange={(e) => onStepChange(Number(e.target.value) || 1)}
              />
            </label>
         );
     }



                 src/components/CounterControls.jsx — child calls parent via callback props


     export default function CounterControls({ onIncrement, onDecrement, onReset }) {
         return (
            <div className="controls">
              <button onClick={onDecrement}>− Decrement</button>
              <button onClick={onIncrement}>+ Increment</button>
              <button onClick={onReset}>Reset</button>
            </div>
         );
     }



                 Output (step set to 5, Increment clicked twice)


     Counter App
     Current count: 10                ← shown in green (count >= 10)
     Step: [ 5 ]
     [ − Decrement ]        [ + Increment ]   [ Reset ]
     Browser tab title: "Count: 10"



  5. HOW STATE AND HOOKS WORK HERE

         useState creates two pieces of state in App ; calling setCount / setStep re-renders App and its
         children with new props.
         useEffect runs after each render in which count changed and updates the tab title (a side effect).

         The child components hold no state: they receive data and callback functions as props (state lifted to
         App).

--- PDF page 276 ---
Functional updates ( c => c + step ) ensure correct results even when updates are batched.

  🎯 Marking scheme guess: 3 M state vs hooks (definitions + table) · 5 M multi-component counter code with useState/useEffect/props · 2
  M output + explanation




    4.13 Context API — Provider, Consumer, useContext
📚 Sources: Unit 4 Notes §9         LEC 9 (React) s.15–16      ShopLite React Manual 2.2, 3.2   One-Shot p.15     Complete Revision deck s.34



▸ The problem: prop drilling
When a deeply nested component needs some data, every component in between must accept it as a prop and
pass it on, even if it never uses it. That is prop drilling. In ShopLite step 2.2, ProductList receives onAdd
only to hand it to ProductCard — and it gets worse with every level.

  Without Context (drilling)                                    With Context

  App — owns user                                               App — Provider holds user

  └ Layout — only passes it                                     └ Layout — does not touch it

    └ Sidebar — only passes it                                    └ Sidebar — does not touch it

      └ Profile — uses user                                         └ Profile — useContext(UserCtx)


Context creates a shared channel: a component high in the tree provides a value, and any component below it
can read it directly, skipping the middle.


▸ The three pieces

                        createContext()                    Provider value={…}                  Consumer / useContext
                        make the channel
                                            →       wrap the tree, supply the value
                                                                                       →         read it anywhere below




  Piece                  Role                                                                   Code

   createCon‐            Creates the channel (argument = default value used when                 const ThemeCtx =
  text                   there is no Provider above)                                            createContext(null)

  Provider               Supplies the value to every component inside it; when the               <ThemeCtx.Provider value=
                         value changes, all consumers re-render                                 {theme}>

  Consumer               Reads the value — older render-prop style (a function as                <ThemeCtx.Consumer>{v => …}
                         child)                                                                 </ThemeCtx.Consumer>

   useContext            Modern, shorter way to read the value                                   const theme =
                                                                                                useContext(ThemeCtx)


           a complete theme example — all three pieces

--- PDF page 277 ---
// src/context/ThemeContext.jsx
  import { createContext, useContext, useState } from "react";


  export const ThemeContext = createContext(null);               // 1. the channel


  export function ThemeProvider({ children }) {                  // 2. Provider component
      const [theme, setTheme] = useState("light");
      const toggle = () => setTheme((t) => (t === "light" ? "dark" : "light"));
      return (
        <ThemeContext.Provider value={{ theme, toggle }}>
           {children}
        </ThemeContext.Provider>
      );
  }


  // 3a. modern consumer
  export function ThemeButton() {
      const { theme, toggle } = useContext(ThemeContext);
      return <button onClick={toggle}>Switch (now {theme})</button>;
  }


  // 3b. classic Consumer (render prop) — same value, older syntax
  export function ThemeLabel() {
      return (
        <ThemeContext.Consumer>
           {({ theme }) => <p className={theme}>Current theme: {theme}</p>}
        </ThemeContext.Consumer>
      );
  }


  // src/App.jsx — wrap the tree once; no props passed to the consumers
  // <ThemeProvider> <ThemeLabel /> <ThemeButton /> </ThemeProvider>



ShopLite uses both consumer styles on the same cart context (step 3.2): the Header uses the classic
Consumer, ProductCard and Cart use the hook.

           src/components/Header.jsx (manual step 3.2)


  import { CartContext } from "../context/CartContext.jsx";


  export default function Header() {
      return (
        <header className="header">
           <span className="brand">ShopLite</span>
           {/* The classic Consumer: a function that receives the shared value */}
           <CartContext.Consumer>

--- PDF page 278 ---
{({ count }) => <span className="badge">Cart: {count}</span>}
           </CartContext.Consumer>
          </header>
      );
  }



  ✍️ EXAM LINE
  "Consumer and useContext do the same job. The syllabus names both, so know the older render-prop
  form, but write useContext in new code." (Unit 4 Notes §9.) In React 19 you may also see
    <ThemeContext value={…}> used directly as the provider — same meaning as .Provider .



  ⚠️ CONTEXT IS NOT FREE
  Every consumer re-renders when the Provider's value changes. Writing value={{ theme, toggle }}
  creates a new object on every render of the provider; for large trees wrap it in useMemo . Use context for
  genuinely global data (user, theme, cart, language), not to avoid passing one prop one level.




      4.14 useReducer and Context + Reducer
📚 Sources: Unit 4 Notes §10–11    LEC 9 (React) s.17–18    ShopLite React Manual 3.1–3.3    One-Shot p.15

 Complete Revision deck s.35


A reducer is a pure function that takes the current state and an action and returns the new state:
 (state, action) => newState . Instead of updating state from many places, components describe what
happened with an action object ( { type: "add", product } ) and one function decides the result. The name
comes from Array.prototype.reduce .

                 Component             dispatch(action)              reducer(state, action)             New state
                     user event
                                  →      { type: "add" }
                                                             →          decides new state
                                                                                                 →      UI re-renders



            the counter reducer (Unit 4 Notes §10)


  import { useReducer } from "react";


  function reducer(state, action) {
      switch (action.type) {
          case "add":
           return { count: state.count + 1 };
          case "reset":
           return { count: 0 };
          default:
           return state;                        // unknown action: unchanged
      }
  }

--- PDF page 279 ---
function Counter() {
      const [state, dispatch] = useReducer(reducer, { count: 0 });                   // (reducer, initialState)
      return (
          <>
              <p>{state.count}</p>
              <button onClick={() => dispatch({ type: "add" })}>+1</button>
              <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
          </>
      );
  }



                        useState                                useReducer

  Best for              Simple, independent values              Complex, related state with several kinds of change

  Update via            The setter                               dispatch(action)

  Logic lives           In event handlers (spread around)       In one reducer (one place, easy to test)



▸ ShopLite's cart reducer (manual step 3.1)

               src/context/cartReducer.js


  export const initialCart = { items: [] };


  // A reducer is a pure function: (state, action) => new state.
  // It never changes the old state; it returns a new one.
  export function cartReducer(state, action) {
      switch (action.type) {
          case "add": {
              const p = action.product;
              const found = state.items.find((i) => i.id === p.id);
              const items = found
                ? state.items.map((i) => (i.id === p.id ? { ...i, qty: i.qty + 1 } : i))
                : [...state.items, { ...p, qty: 1 }];
              return { items };
          }
          case "remove":
              return { items: state.items.filter((i) => i.id !== action.id) };
          case "clear":
              return initialCart;
          default:
              return state;
      }
  }

--- PDF page 280 ---
⚠️ A REDUCER MUST BE PURE
  No push , no assigning to state , no fetching, no random values, no Date.now() . Same input → same
  output. { ...i, qty: i.qty + 1 } builds a new object instead of editing the old one. The default
  branch returns the state unchanged for unknown actions.



▸ Context + Reducer = a small global store
A Provider component holds the state with useReducer and puts { state, dispatch } into context. Any
component below can read the state and dispatch actions — no props in between.


                                                                  CartProvider
                                                      useReducer(cartReducer, initialCart)
                                                      value = { state, dispatch, count, total }


            state flows down ↓                                                                                 actions flow up ↑


                        Header                                     ProductCard                            Cart
                reads count (Consumer)                          dispatch({type:"add"})            reads items, dispatch


                                                       The ShopLite store (manual step 3.2)


 Step                            What you do                      Code

 1. Create context               Make the channel                  createContext(null)

 2. Hold state in                State and dispatch live here      useReducer(reducer, init)
 Provider

 3. Wrap the app                 Everything inside can read        <CartProvider><App /></CartProvider> in main.jsx
                                 it                               (§4.2)

 4. Consume anywhere             Read state, call dispatch         useContext(CartContext) via useCart()


            src/context/CartContext.jsx (manual step 3.2)


  import { createContext, useContext, useReducer } from "react";
  import { cartReducer, initialCart } from "./cartReducer.js";


  // 1. Create the channel.
  export const CartContext = createContext(null);


  // 2. A Provider holds the state and supplies it to everything inside it.
  export function CartProvider({ children }) {
     const [state, dispatch] = useReducer(cartReducer, initialCart);


     const count = state.items.reduce((n, i) => n + i.qty, 0);
     const total = state.items.reduce((sum, i) => sum + i.price * i.qty, 0);


     return (
        <CartContext.Provider value={{ state, dispatch, count, total }}>

--- PDF page 281 ---
{children}
        </CartContext.Provider>
      );
  }


  // 3. A short helper (a custom hook) so components write useCart().
  export function useCart() {
      return useContext(CartContext);
  }



             src/components/Cart.jsx (manual step 3.3, excerpt) — a second consumer, connected by no prop


  import { useCart } from "../context/CartContext.jsx";


  export default function Cart() {
      const { state, dispatch, total } = useCart();
      return (
        <aside className="cart">
            <h2>Your cart</h2>
            <ul>
              {state.items.map((i) => (
                <li key={i.id}>
                    {i.name} × {i.qty}
                    <button onClick={() => dispatch({ type: "remove", id: i.id })}>✕</button>
                </li>
              ))}
            </ul>
            <p className="total">Total: ₹{total.toLocaleString("en-IN")}</p>
            <button onClick={() => dispatch({ type: "clear" })}>Clear cart</button>
        </aside>
      );
  }



Follow one click (manual step 3.3): button → dispatch({ type: "add", product }) → reducer returns a
new cart → CartProvider re-renders → every consumer (Header badge, Cart panel, tab title) shows the new
value. Add the Keyboard twice and the Mouse once: "Mechanical Keyboard × 2, Wireless Mouse × 1, Total:
₹7,797".


   ✏️ FILL IN THE BLANKS — CONTEXT + RED U CE R
               AuthContext.jsx


      import { createContext, useContext, __(1)__ } from "react";


      function authReducer(state, action) {
           switch (action.__(2)__) {

--- PDF page 282 ---
case "login":      return { user: action.user };
             case "logout": return { user: null };
             __(3)__:           return state;
         }
     }


     export const AuthContext = __(4)__(null);


     export function AuthProvider({ children }) {
         const [state, __(5)__] = useReducer(authReducer, { user: null });
         return (
             <AuthContext.__(6)__ value={{ state, dispatch }}>
               {__(7)__}
             </AuthContext.Provider>
         );
     }


     export const useAuth = () => __(8)__(AuthContext);
     // in a component:          const { dispatch } = useAuth();                dispatch({ type: "logout" });



   🔓 Answer key: (1) useReducer (2) type (3) default (4) createContext (5) dispatch (6) Provider (7) children (8) useContext


    4.15 API handling — fetch, axios, loading and errors
📚 Sources: Unit 4 Notes §12–13        LEC 9 (React) s.19–20      ShopLite React Manual 4.2    One-Shot p.16

 Complete Revision deck s.36


To show real data, React asks the backend for it over HTTP. The usual place is a useEffect that runs when the
component mounts; the JSON that comes back is put into state, which re-renders the UI.

                 Mounts      →       useEffect      →         fetch / axios    →      Django REST         →       JSON         →

                                                          setState → re-render


              fetch inside useEffect (Unit 4 Notes §12)


  useEffect(() => {
     async function load() {
         const res = await fetch("/api/products/");
         const data = await res.json();
         setProducts(data);
     }
     load();                 // the effect itself cannot be async, so define and call
  }, []);

--- PDF page 283 ---
▸ fetch vs axios

                          fetch                                      axios

  Built in                Yes (browser API)                          Install it: npm install axios

  JSON                    Extra res.json() step                      Automatic: res.data

  Sending JSON            Set headers + JSON.stringify(body)          api.post(url, data) does both
                          yourself

  HTTP errors             Does not throw on 404/500 — check res.ok   Throws on any non-2xx status

  Interceptors / base     No                                         Yes ( axios.create , auth headers in one
  URL                                                                place)



  ⚠️ THE FETCH ERROR TRAP
  A 404 or 500 is still a "successful" fetch — the promise resolves. You must write
    if (!res.ok) throw new Error(`HTTP ${res.status}`) . axios throws, so a normal try / catch han‐
  dles it (manual: a typo /produts/ gives "Request failed with status code 404").



▸ One configured client (manual steps 4.2 and 5.1)

             src/api.js


  import axios from "axios";


  // One configured axios client for the whole app.
  const api = axios.create({
      baseURL: import.meta.env.VITE_API_URL, // set in .env, so deploying needs no code change
  });


  export default api;


  // Django REST sends validation errors as { field: ["message", ...] }. Make one sentence.
  export function errorText(err) {
      const data = err.response?.data;
      if (!data || typeof data !== "object") return err.message;
      return Object.entries(data)
        .map(([field, msgs]) => `${field}: ${[].concat(msgs).join(" ")}`)
        .join(" · ");
  }



Components then write api.get("/products/") and never repeat the server address.

--- PDF page 284 ---
▸ Loading, error and success — every request has three outcomes

  Status                State                                        What the user sees

  Loading                loading = true                              Spinner or "Loading…"

  Success                products is set                             The list

  Error                  error is set                                Message and a "Try again" button


              src/App.jsx — the request part (manual step 4.2)


  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");


  async function load() {
       setLoading(true);
       setError("");
       try {
           const res = await api.get("/products/");
           setProducts(res.data);
       } catch (err) {
           setError(err.message);        // "Network Error" / "Request failed with status code 404"
       } finally {
           setLoading(false);                     // runs on success AND failure
       }
  }


  useEffect(() => {
       load();
  }, []);


  // in the JSX
  {loading && <p className="status">Loading…</p>}
  {error && (
       <p className="status error">
           {error} <button className="btn small" onClick={load}>Try again</button>
       </p>
  )}
  {!loading && !error && <ProductList products={visible} />}


Stop Django and reload: "Network Error" with a retry button. Start Django and click Try again: the products return without a page
refresh.


▸ Packaging it as a custom hook

              src/useFetch.js — reusable loading/error/success with a stale-response guard

--- PDF page 285 ---
import { useEffect, useState } from "react";
  import api from "./api.js";


  export function useFetch(url) {
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState("");


      useEffect(() => {
        let ignore = false;
        setLoading(true);
        setError("");
        api.get(url)
           .then((res) => { if (!ignore) setData(res.data); })
           .catch((err) => { if (!ignore) setError(err.message); })
           .finally(() => { if (!ignore) setLoading(false); });
        return () => { ignore = true; };
      }, [url]);


      return { data, loading, error };
  }


  // usage in any component:
  // const { data: products, loading, error } = useFetch("/products/");




      4.16 CRUD from React to Django REST
📚 Sources: Unit 4 Notes §14      LEC 9 (React) s.21   ShopLite React Manual 4.1, 4.3   One-Shot p.16    Complete Revision deck s.36


CRUD = Create, Read, Update, Delete. Each maps to an HTTP method, a Django REST endpoint and an axios
call. On the Django side one ModelViewSet registered with a router provides all of them.

  Operation      HTTP             DRF endpoint                React call                                            Success status

  Read all       GET               /api/products/              api.get("/products/")                                200 OK

  Read one       GET               /api/products/5/            api.get("/products/5/")                              200 OK

  Create         POST              /api/products/              api.post("/products/", data)                         201 Created

  Update         PUT / PATCH       /api/products/5/            api.patch("/products/5/", changes)                   200 OK

  Delete         DELETE            /api/products/5/            api.delete("/products/5/")                           204 No Content


PUT replaces the whole object (send every field); PATCH changes only the fields you send. Validation failures come back as 400 with
 { "field": ["message"] } .

--- PDF page 286 ---
▸ The Django side (what ShopLite's provided backend does, simplified)

           backend — models.py, serializers.py, views.py, urls.py


  # products/models.py
  from django.db import models


  class Product(models.Model):
        name = models.CharField(max_length=100)
        price = models.FloatField()
        category = models.CharField(max_length=50)
        in_stock = models.BooleanField(default=True)
        description = models.TextField(blank=True)


  # products/serializers.py
  from rest_framework import serializers
  from .models import Product


  class ProductSerializer(serializers.ModelSerializer):
        class Meta:
             model = Product
             fields = ["id", "name", "price", "category", "in_stock", "description"]


        def validate_price(self, value):
             if value <= 0:
                   raise serializers.ValidationError("Price must be greater than zero.")
             return value


  # products/views.py
  from rest_framework import viewsets
  from .models import Product
  from .serializers import ProductSerializer


  class ProductViewSet(viewsets.ModelViewSet):           # list, retrieve, create, update, destroy
        queryset = Product.objects.all()
        serializer_class = ProductSerializer


  # config/urls.py
  from django.urls import path, include
  from rest_framework.routers import DefaultRouter
  from products.views import ProductViewSet


  router = DefaultRouter()
  router.register("products", ProductViewSet)
  urlpatterns = [path("api/", include(router.urls))]

--- PDF page 287 ---
terminal — start the provided API (manual step 4.1, macOS/Linux)


  cd ../backend && python3 -m venv venv && source venv/bin/activate
  pip install -r requirements.txt && cp .env.example .env
  python manage.py migrate && python manage.py seed
  python manage.py runserver              # http://localhost:8000/api/products/




▸ The React side — write, then update state from the server's answer

            src/App.jsx — create, delete (manual step 4.3) and update


  async function addProduct(data) {
      const res = await api.post("/products/", data);
      setProducts([...products, res.data]);        // the SERVER's object: it has the new id
  }


  async function removeProduct(id) {
      await api.delete(`/products/${id}/`);
      setProducts(products.filter((p) => p.id !== id));
  }


  // PATCH, which the manual describes but skips building:
  async function updatePrice(id, price) {
      const res = await api.patch(`/products/${id}/`, { price });
      setProducts((prev) => prev.map((p) => (p.id === id ? res.data : p)));
  }


  // passed down as props:
  <AddProductForm onAdd={addProduct} />
  <ProductList products={visible} onDelete={removeProduct} />



            src/components/AddProductForm.jsx — submit handler (manual step 4.3)


  async function handleSubmit(e) {
      e.preventDefault();                 // stop the browser reloading the page
      try {
          await onAdd(form);              // App posts it to Django
          setForm(emptyForm);
          setMessage("Product added.");
      } catch (err) {
          // e.g. "name: This field may not be blank. · price: A valid number is required."
          setMessage(errorText(err));
      }
  }

--- PDF page 288 ---
✍️ TWO RULES THE EXAMINER LIKES
    1. Wait for the server, then update state — and add res.data , not the form data you sent: only the
        server knows the new id .
    2. Never trust the browser alone — React checks are for convenience; the serializer's validation
        ( validate_price ) is the real protection.



   ✏️ COMPLETE THE CRUD CALLS
    1. Read the list: const res = await api.                                 ("/products/"); setProducts(res.                           );

    2. Create: await api.                        ("/products/", form) → expected status

    3. Change only the price of product 5: api.                                ("/products/5/", { price: 899 })

    4. Delete product 5: api.                          (`/products/${id}/`) → expected status

    5. DRF class that provides all five routes: viewsets.                                 ; registered with
                        ().register("products", ProductViewSet)

    6. With fetch , a 404 response must be detected with if (!res.                                         )


   🔓 Answer key: 1) get · data 2) post · 201 3) patch 4) delete · 204 5) ModelViewSet · DefaultRouter 6) ok


    4.17 Backend connectivity and authentication
📚 Sources: Unit 4 Notes §15–17        LEC 9 (React) s.22–23        ShopLite React Manual 5.1, 5.2, Troubleshooting    One-Shot p.16

 Complete Revision deck s.36




                                             request                                         ORM query
               React (Vite)                                      Django REST                                         Database
               localhost:5173                                     localhost:8000                                PostgreSQL / SQLite
                  UI + state                                     views, serializers                                products table
                                             JSON                                               rows

                            different port = different origin → CORS


                                Two separate programs talking HTTP + JSON (Unit 4 Notes §15.1, manual 5.1)


  Topic        What it is                                                             How it is done

  CORS         Browsers block a page from reading responses from a                    Install django-cors-headers , allow
               different origin by default                                            http://localhost:5173

  Base         The API address                                                        Keep it in .env as VITE_API_URL , so deploying
  URL                                                                                 needs no code change

  Dev          Avoids CORS during development                                         Vite server.proxy forwards /api to Django
  proxy

--- PDF page 289 ---
▸ CORS — break it, read it, fix it
An origin = protocol + host + port. http://localhost:5173 and http://localhost:8000 are different ori‐
gins. The browser sends the request, Django answers (Network tab shows 200), but the browser refuses to let
your JavaScript read the answer unless the response carries an Access-Control-Allow-Origin header
naming your page's origin. Console: "…has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
header is present". CORS is enforced by browsers only — that is why Postman and curl never hit it.

           backend: pip install django-cors-headers → config/settings.py


  INSTALLED_APPS = [
        # ...
        "rest_framework",
        "corsheaders",
        "products",
  ]


  MIDDLEWARE = [
        "corsheaders.middleware.CorsMiddleware",         # high up: before CommonMiddleware
        "django.middleware.common.CommonMiddleware",
        # ...
  ]


  # the ShopLite starter reads this list from CORS_ORIGINS in backend/.env
  CORS_ALLOWED_ORIGINS = ["http://localhost:5173"]




▸ Environment variable and the Vite proxy

           frontend/.env (manual step 5.1)


  # only VITE_-prefixed variables reach the code, read as import.meta.env.VITE_API_URL
  # Vite reads .env only at startup: restart npm run dev after editing
  VITE_API_URL=http://localhost:8000/api



           vite.config.js — optional dev proxy (manual step 5.2)


  import { defineConfig } from "vite";
  import react from "@vitejs/plugin-react";


  export default defineConfig({
      plugins: [react()],
      server: {
        port: 5173,
        // Forward /api/... to Django, so the browser only ever talks to port 5173.
        proxy: { "/api": "http://localhost:8000" },
      },

--- PDF page 290 ---
});
  // with the proxy, set VITE_API_URL=/api: same origin, so no CORS in development



  ⚠️ CONNECTIVITY ERRORS FROM THE MANUAL
        Network Error — Django is not running, or CORS_ORIGINS does not exactly match the page's origin
        (e.g. Vite moved to port 5174).
        Blank page, "products.filter is not a function" — .env missing or Vite not restarted: axios asked the
        page's own address and Vite returned HTML instead of JSON.
        Secrets in VITE_ variables — everything in them is shipped to every visitor's browser. API address
        yes; passwords and secret keys never.
        The proxy exists only in the dev server. In production you enable CORS for the real domain, or serve
        frontend and API from one host (e.g. nginx in front of both).



▸ Authentication flow with tokens

 1        Login form — user types username + password (controlled inputs).

 2        POST /api/token/ — React sends the credentials to Django.

 3        Token returned — with djangorestframework-simplejwt : { "access": "…", "refresh": "…" } (a
          JWT).

 4        Store the token — in context (memory) or storage; production apps prefer an httpOnly cookie (Java‐
          Script cannot read it, so XSS cannot steal it).

 5        Send it on each call — header Authorization: Bearer <token> . (DRF's simpler
           TokenAuthentication uses Authorization: Token <key> instead.)


 6        Protected route — pages that need a login redirect visitors without a token to /login ; Django pro‐
          tects the data itself with permission_classes = [IsAuthenticated] (401 if missing).


           Django — urls.py (SimpleJWT)


  from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView


  urlpatterns += [
        # POST {username, password} -> {access, refresh}
        path("api/token/", TokenObtainPairView.as_view()),
        # POST {refresh} -> new access token
        path("api/token/refresh/", TokenRefreshView.as_view()),
  ]
  # settings.py: REST_FRAMEWORK = {"DEFAULT_AUTHENTICATION_CLASSES":
  #        ["rest_framework_simplejwt.authentication.JWTAuthentication"]}



           React — login, send the token, protect a route

--- PDF page 291 ---
// login (inside an AuthProvider that holds token in state and shares it via context)
  async function login(username, password) {
      const res = await api.post("/token/", { username, password });
      setToken(res.data.access);                                           // context: UI knows we are logged in
      localStorage.setItem("access", res.data.access);                     // lab option; httpOnly cookie in prod
  }


  // send it on one call (Unit 4 Notes §16) ...
  axios.get(url, { headers: { Authorization: `Bearer ${token}` } });


  // ... or on EVERY call with an interceptor (the neat way)
  api.interceptors.request.use((config) => {
      const token = localStorage.getItem("access");
      if (token) config.headers.Authorization = `Bearer ${token}`;
      return config;
  });


  // protected route (React Router)
  import { Navigate } from "react-router-dom";


  function Protected({ children }) {
      const { token } = useAuth();
      return token ? children : <Navigate to="/login" replace />;
  }
  // <Route path="/admin" element={<Protected><AdminPage /></Protected>} />


Authentication is shown in the slides as a demonstration and is not part of the ShopLite lab (Unit 4 Notes §16).




      4.18 Rendering architectures: CSR, SSR, SSG and RSC
📚 Sources: Not in your files — added from standard references (react.dev Server Components, Next.js App Router docs)
 Link to course: ShopLite is a CSR app (ShopLite React Manual 0.3, 4.2)


      🚨 NOT IN YOUR STUDY MATERIAL · 20 MARKS · FINAL 2025-26 Q4(A, B, C)
      Gap G1 — the biggest gap in the whole subject. The newest paper spent an entire question (10 + 6 + 4
      marks) on React Server Components vs Client-Side Rendering vs Server-Side Rendering, SPA vs
      RSC, and how a Django backend serves each. Words like SSR, hydration, RSC, Next.js, "use client" or
      streaming appear in none of your 22 study files.

      Verdict: MUST LEARN. The newest paper sets the style for 2026, and this topic is a natural repeat.
      Skipping it means you must answer four of the remaining five long questions with no choice left. The good
      news: it is conceptual — no long code to memorise. Learn the timeline picture, the big comparison table
      and the three model answers in §4.18–4.20.

--- PDF page 292 ---
🧠 START FROM ZERO — THE ONE QUESTION BEHIND ALL FOUR TERMS
  Your React components must become pixels in a browser. The architectures differ only in where the com‐
  ponents run (browser or server), when (per request, at build time) and what travels over the network
  (empty HTML + JavaScript, finished HTML, or a serialized component tree). Keep asking those three
  questions and every comparison writes itself.


 Term            Meaning

 Bundle          The JavaScript file(s) the browser must download to run your React code

 Hydration       React running in the browser over server-made HTML and attaching event handlers so the static page becomes interac‐
                 tive ( hydrateRoot )

 TTFB            Time To First Byte — how long until the server starts answering

 FCP /           First / Largest Contentful Paint — when the first / main content becomes visible
 LCP

 TTI             Time To Interactive — when clicks and typing actually work (Core Web Vitals now track responsiveness as INP)

 SEO             Search Engine Optimisation — crawlers and link previews read the HTML; content that only appears after JavaScript runs
                 is indexed late or not at all

 CDN             Content Delivery Network — servers worldwide that cache static files close to users




   CSR                     HTML             download JS bundle (big)                run React           fetch JSON from API               render
                                                                                                                                                   FCP ≈ TTI
   Vite SPA                                                                                                                                        (late)

                        user sees a blank page / spinner until the very end




   SSR
                              server: data + full HTML              download ALL component JS                  hydrate all          TTI
   + hydration

                                                               FCP early: content visible, but buttons do nothing until hydration




   RSC                      server components            small client JS      hydrate islands TTI
   Next.js App Router
                                                                slow parts stream in (Suspense)

                        FCP early (HTML streamed); only "use client" parts ship JS and hydrate


                                                                                                                                                            time →

The same product page under three architectures (illustrative, not to scale). Green = work on the server, amber = JS download, violet = JS execu‐
                                                                           tion in the browser.



▸ 1 · Client-Side Rendering (CSR)
All rendering happens in the browser. The server sends an almost empty HTML page plus a JavaScript bun‐
dle; React builds the whole UI in the browser and then fetches data from APIs. Your ShopLite app is CSR :
 index.html contains only <div id="root"></div> , main.jsx calls createRoot(...).render(<App />) ,
and App fetches /api/products/ in a useEffect .

 1         Browser requests the page → gets the HTML shell (no content) from a static host/CDN.

--- PDF page 293 ---
2         Downloads and runs the JS bundle (React + all your components).

 3         React renders — the first screen is usually a spinner ("Loading…").

 4         useEffect calls the API (Django REST) → JSON → setState → re-render with real data.


            what the browser receives first in CSR (view-source of ShopLite)


  <body>
     <div id="root"></div>                                         <!-- empty: no products -->
     <script type="module" src="/assets/index-3f9a.js"></script>                 <!-- all UI -->
  </body>




  STRENGTHS                                                       WEAKNESSES

       Very interactive, app-like; fast navigation after               Slow first paint: HTML → JS → data waterfall;
       the first load (no page reloads)                                blank screen on slow phones/networks
       Simple hosting: static files on any CDN; server                 Large bundles: every component's JS is
       only serves JSON                                                shipped
       Clear separation: frontend and backend deploy                   Weak SEO / link previews (content not in the
       independently                                                   HTML)


Use for: dashboards, admin panels, internal tools, apps behind a login (SEO irrelevant), highly interactive
editors.


▸ 2 · Server-Side Rendering (SSR) + hydration
On every request, the server runs the React components and sends finished HTML with the data already in
it, so the user sees content immediately. The browser then downloads the same component JavaScript and hy‐
drates the page — React re-runs the components in the browser, matches them to the existing HTML and at‐
taches event handlers. Frameworks: Next.js (Pages Router), Remix / React Router, or plain react-dom/server .

 1         Request arrives → the server fetches the data (DB or API) for this page.

 2         Server renders React to HTML ( renderToString / renderToPipeableStream ) and embeds the data
           as JSON for hydration.

 3         Browser shows the HTML at once (good FCP/LCP, crawlers see everything) — but buttons do not
           work yet.

 4         Browser downloads the JS bundle and hydrates ( hydrateRoot ) → the page becomes interactive
           (TTI).


            SSR in Next.js Pages Router — data fetched on the server per request


  // pages/products.jsx
  // runs ONLY on the server, on every request

--- PDF page 294 ---
export async function getServerSideProps() {
       const res = await fetch("http://localhost:8000/api/products/");
       const products = await res.json();
       return { props: { products } };          // serialized into the page for hydration
  }


  // runs on the server (HTML) AND again in the browser (hydration)
  export default function Products({ products }) {
       return (
        <ul>
            {products.map((p) => (
             <li key={p.id}>
                  {p.name} <button onClick={() => alert(p.name)}>Buy</button>
             </li>
            ))}
        </ul>
       );
  }
  // under the hood:       server   -> renderToString(<Products ... />)
  //                        browser -> hydrateRoot(root, <Products ... />)




  STRENGTHS                                                   WEAKNESSES
        Fast FCP/LCP — content in the first response               Higher TTFB and server cost: render on every
        Excellent SEO and social previews                          request

        Fresh, per-user data on every request                      Still ships all component JS and hydrates the
                                                                   whole page — "looks ready but is not click‐
                                                                   able" gap
                                                                   Hydration mismatch errors if server and brows‐
                                                                   er output differ (e.g. Date.now() , window )


Use for: SEO-critical pages with dynamic or personalised data — e-commerce product pages, news, search re‐
sults, social feeds.


▸ 3 · Static Site Generation (SSG) — briefly
Render the pages to HTML once at build time ( npm run build ), then serve the files from a CDN. Fastest pos‐
sible TTFB and cheapest hosting, perfect SEO — but content is only as fresh as the last build. ISR (Incremental
Static Regeneration) re-builds individual pages in the background every N seconds. Use for: blogs, documenta‐
tion, marketing and landing pages. (Classic Django templates are the opposite — HTML rendered by the server
on every request: traditional SSR.)

--- PDF page 295 ---
▸ 4 · React Server Components (RSC)
React Server Components are a new kind of component (stable in React 19; the default in the Next.js App
Router since 2023) that run only on the server. Their code is never sent to the browser, they can be async
and read data directly (database, file system, internal APIs, secret keys), and they produce a serialized descrip‐
tion of the UI. Components that need interactivity are marked as Client Components with the "use client"
directive; only those ship JavaScript and hydrate.


                                                            app/products/page.jsx
                                                         Server · async · awaits Django API




                        Header                                        ProductList                                         SearchBox
                  Server · 0 KB JS                              Server · maps products                                "use client" · useState




                                                 ProductCard                             AddToCartButton
                                               Server · markup only                      "use client" · onClick

             Server Component: runs on server, code never shipped, can await data                  Client Component: JS shipped + hydrated


                             An RSC tree: most of the page is server-only; interactivity lives in small client "islands".


SERVER VS CLIENT COMPONENTS

                     Server Component (default)                                 Client Component ( "use client" )

  Runs               Only on the server (per request or at build                Pre-rendered to HTML on the server, then hydrated and
                     time)                                                      run in the browser

  JS sent to         None (zero bundle size)                                    Yes
  browser

  Can use               async/await , DB queries, file system, se‐                useState , useEffect , event handlers ( onClick ),
                     cret env vars, server-only libraries                       browser APIs ( window , localStorage )

  Cannot use         State, effects, event handlers, browser APIs               Direct DB access or secrets (it runs in the user's browser)


            app/products/page.jsx — a Server Component (Next.js App Router)


  import AddToCartButton from "./AddToCartButton";


  export default async function ProductsPage() {                                               // async: server only
     const res = await fetch(`${process.env.DJANGO_API_URL}/products/`, {
         next: { revalidate: 60 },                                                             // cache the result for 60 s
     });
     const products = await res.json();                       // DJANGO_API_URL never reaches the browser


     return (
         <main>
           <h1>Products</h1>

--- PDF page 296 ---
<ul>
               {products.map((p) => (
                <li key={p.id}>
                     {p.name} — ₹{p.price}
                     <AddToCartButton id={p.id} />                          {/* client island */}
                </li>
               ))}
           </ul>
         </main>
      );
  }



           app/products/AddToCartButton.jsx — a Client Component


  "use client";                   // boundary: this file and its imports ship to the browser
  import { useState } from "react";


  // props coming from a Server Component must be serializable (no functions)
  export default function AddToCartButton({ id }) {
      const [added, setAdded] = useState(false);
      return (
         <button onClick={() => setAdded(true)}>
           {added ? "Added ✓" : "Add to cart"}
         </button>
      );
  }



WHAT IS ACTUALLY SENT TO THE BROWSER

 1. HTML (first load only) — a fast, non-interactive preview of the whole page, like SSR.
 2. The RSC payload — a compact, streamable serialization of the rendered server tree: the output of Server
      Components, placeholders where Client Components go with references to their JS files, and the props
      passed to them.
 3. JavaScript only for Client Components, which React hydrates. The Server Components' code, their li‐
      braries (markdown parsers, date libraries, ORM clients) and their data-fetching logic never ship.

           the RSC payload — simplified illustration (real format is internal to React)


  1:I["app/products/AddToCartButton.jsx", ["chunk-77.js"], "default"]            ← client component ref
  0:["$","main",null,{"children":[
         ["$","h1",null,{"children":"Products"}],
         ["$","ul",null,{"children":[
           ["$","li","1",{"children":["Wireless Mouse — ₹799", ["$","$L1",null,{"id":1}]]}]
         ]}]
  ]}]                                                ← already-rendered server output

--- PDF page 297 ---
STREAMING WITH SUSPENSE
A slow part of the page does not have to block the rest. Wrap it in <Suspense> : the server immediately streams
the shell with the fallback, then streams the slow component's output into place when its data arrives (in Next.js
a loading.jsx file does this for a whole route).

              app/products/[id]/page.jsx — streaming


  import { Suspense } from "react";


  export default async function ProductPage({ params }) {
      const { id } = await params;
      return (
         <>
           <ProductDetails id={id} />                  {/* fast: sent first */}
           <Suspense fallback={<p>Loading reviews…</p>}>
               <Reviews id={id} />                     {/* slow async component: streamed later */}
           </Suspense>
         </>
      );
  }



NAVIGATION, MUTATIONS AND CACHING

      Navigation: clicking a <Link> does not reload the page; the client router fetches the RSC payload for the
      new route (prefetched in advance) and merges it into the tree, keeping client state such as an open cart.
      Mutations: Server Functions / Server Actions ( "use server" ) let a form call server code directly; the
      server then re-renders the affected route. Note: "use server" marks server functions, not Server
      Components — Server Components need no directive.
      Caching: rendered output and fetch results can be cached on the server and revalidated on a timer
      ( revalidate: 60 ) or on demand ( revalidatePath ), so many users can share one render.

  ⚠️ RSC IS NOT "SSR WITH A NEW NAME"
  SSR is about producing HTML on the server for the first load — but every component still ships its
  JavaScript and the whole page hydrates. RSC is about which components exist in the browser at all: Server
  Components never ship or hydrate, they can fetch data directly, and they keep working on navigation (RSC
  payload, not HTML). The two are complementary: Next.js uses RSC for the server parts and SSR to turn
  the first render (including Client Components) into HTML.


  ⚠️ LIMITS OF RSC
  Needs a framework and a running JavaScript server (Next.js, or a static export); a new mental model
  (server/client boundary, "which file am I in?"); props crossing the boundary must be serializable (no func‐
  tions except Server Actions); every navigation needs a server round trip; more server compute and caching
  decisions; harder debugging across two environments.

--- PDF page 298 ---
▸ The big comparison table

 Aspect             CSR                                  SSR                                    RSC

 Where code         Browser only                         Server (per request) and browser       Server Components: server only. Client
 runs                                                    (hydration) — same components          Components: server (HTML) + browser
                                                         twice

 Data fetching      Browser calls APIs after JS loads    Server fetches before rendering        Inside async Server Components,
                    ( useEffect /axios) — HTML →         ( getServerSideProps , load‐           close to the DB/API; secrets stay on
                    JS → data waterfall                  ers); data serialized into the page    server; parallel + streamed

 Sent to            Empty HTML shell + full JS bundle;   Full HTML + full JS bundle + serial‐   HTML (first load) + RSC payload + JS
 browser            then JSON                            ized data                              for client components only

 JS bundle          Largest                              Large (all components)                 Smallest — server code is zero-bundle

 FCP / LCP          Slow (blank until JS + data)         Fast                                   Fast, plus streaming

 TTI                = FCP, late                          Delayed by whole-page hydration        Earlier: only client islands hydrate

 SEO                Weak                                 Strong                                 Strong

 Server load /      Lowest: static files on CDN + JSON   High: render per request; Node         Server render per request (cacheable);
 hosting            API                                  server                                 Node server

 Navigation         Client-side, instant after load      Client-side after hydration (frame‐    Client-side; fetches RSC payload per
                                                         work router)                           route

 When to use        Dashboards, admin, logged-in tools   SEO pages with per-request data        Content- and data-heavy apps that
                                                                                                also need interactivity (shops, news,
                                                                                                SaaS)

 Example            Vite + React (ShopLite)              Next.js Pages Router, Remix            Next.js App Router
 stack



   PYQ        Final 2025-26 · Q4(A)   ★ LATEST                                                                                  10 M


  Explain in detail what React Server Components (RSC) are and how they differ from Client-Side
  Rendering (CSR) and Server-Side Rendering (SSR). For each (RSC, CSR, SSR) explain: where the
  code runs; how data is fetched/sent to the client; what gets sent to the browser; performance impli‐
  cations; when to use each.

   ✓     MODEL ANSWER — WRITE THIS


  INTRODUCTION
  React components can be rendered in the browser, on the server, or split between both. The three ap‐
  proaches differ in where components execute, how data reaches them, and what travels over the
  network.

  1. CLIENT-SIDE RENDERING (CSR)

        Where code runs: entirely in the browser. The server only hosts static files.
        Data: after the JS loads, components fetch JSON from a REST API (e.g. Django REST) in useEffect
        using fetch/axios, then setState re-renders.

--- PDF page 299 ---
Sent to browser: an empty HTML shell ( <div id="root"></div> ) + the full JavaScript bundle; later,
       JSON responses.
       Performance: slow first paint (blank/spinner during the HTML → JS → data waterfall), large bundles,
       weak SEO; but very fast, smooth navigation afterwards and cheap hosting (CDN).
       Use when: dashboards, admin panels, apps behind login where SEO does not matter (e.g. a Vite +
       React app).

  2. SERVER-SIDE RENDERING (SSR)

       Where code runs: on the server for every request (renders components to HTML), and again in the
       browser during hydration, when React attaches event handlers to the server HTML.
       Data: fetched on the server before rendering (e.g. getServerSideProps ) and embedded in the HTML;
       also serialized as JSON so the client can hydrate.
       Sent to browser: fully rendered HTML + the JS bundle for all components + serialized data.
       Performance: fast FCP and good SEO; but higher TTFB and server cost (render per request), the whole
       bundle is still downloaded, and the page is not interactive until hydration finishes.
       Use when: SEO-critical pages with fresh or personalised data — product pages, news, search results.

  3. REACT SERVER COMPONENTS (RSC)

  RSCs are components that run only on the server and whose code is never shipped to the browser.
  Interactive parts are separate Client Components marked "use client" . Used through frameworks such
  as the Next.js App Router (stable in React 19).

       Where code runs: Server Components on the server only (per request or at build time); Client
       Components are pre-rendered on the server and hydrated in the browser.
       Data: Server Components are async and fetch data directly — await a database query or an internal
       API call — close to the data, with secrets kept on the server; no client-side fetching waterfall.
       Sent to browser: HTML for the first load, the RSC payload (a serialized description of the rendered tree
       with placeholders for client components), and JavaScript only for Client Components. Output can be
       streamed with <Suspense> .
       Performance: much smaller bundles (zero-bundle server components), less hydration, early FCP via
       streaming, good SEO; costs: server compute, framework dependency and a more complex server/client
       mental model.
       Use when: content- and data-heavy apps that also need interactivity — e-commerce, blogs/news with
       comments, large SaaS apps wanting fast loads and small bundles.

              RSC example (Next.js)


     // app/products/page.jsx — Server Component
     export default async function Page() {
        const products = await (await fetch(process.env.API_URL + "/products/")).json();
        return (
           <ul>
             {products.map((p) => <li key={p.id}>{p.name} <AddButton id={p.id} /></li>)}
           </ul>
        );

--- PDF page 300 ---
}


     // app/products/AddButton.jsx — Client Component
     "use client";
     import { useState } from "react";
     export default function AddButton({ id }) {
         const [added, setAdded] = useState(false);
         return <button onClick={() => setAdded(true)}>{added ? "Added" : "Add"}</button>;
     }



  4. COMPARISON

    Aspect              CSR                              SSR                            RSC

    Code runs           Browser                          Server + browser (hydration)   Server only (client components also in browser)

    Data fetching       Browser → API after load         Server, per request            Server, inside components (direct DB/API)

    Sent to browser     Empty HTML + full JS             Full HTML + full JS + data     HTML + RSC payload + client JS only

    First paint / SEO   Slow / weak                      Fast / strong                  Fast (streaming) / strong

    JS size             Large                            Large                          Small

    Server cost         Low                              High                           Medium–high (cacheable)

    Best for            Dashboards, internal apps        SEO + dynamic pages            Data-heavy apps with islands of interactivity


  Conclusion: CSR maximises interactivity and simplicity, SSR improves first load and SEO at the cost of
  server work and full hydration, and RSC moves non-interactive components and data fetching to the server
  entirely, sending far less JavaScript. Modern frameworks combine them — RSC for most of the page, SSR
  for the first HTML, and client components for interactivity.

  🎯 Marking scheme guess: 2 M RSC definition (server-only, "use client", payload) · 2 M each for CSR, SSR, RSC across the five points (6
  M) · 2 M comparison table + when to use + conclusion




   ✏️ WHICH ARCHITECTURE? WRITE CSR, S SR, S S G OR RS C
    1. The HTML is only <div id="root"></div> ; the products appear after a useEffect call.
    2. HTML is produced once during npm run build and served from a CDN.
    3. An async component awaits a database query and none of its code reaches the browser.
    4. The page arrives fully rendered, then the whole page is hydrated with the full bundle.
    5. The directive that marks a client boundary:                             · the process of attaching event handlers to
         server HTML:
    6. What a Next.js App Router navigation fetches from the server instead of HTML: the

   🔓 Answer key: 1) CSR 2) SSG 3) RSC 4) SSR 5) "use client" · hydration 6) RSC payload

--- PDF page 301 ---
4.19 SPA vs RSC architecture
📚 Sources: Not in your files — added from standard references     ShopLite = an SPA (ShopLite React Manual 0.3)


A Single-Page Application (SPA) loads one HTML page once; after that, JavaScript swaps components in and
out and fetches data as JSON — the browser never loads a new page. Routing is done in the browser (React
Router). SPAs are almost always CSR. The opposite is a Multi-Page Application (MPA) — every link loads a
new HTML page from the server (classic Django templates). The RSC architecture (Next.js App Router) is a hy‐
brid: server-rendered like an MPA on the first load, but navigates without full reloads like an SPA.

           SPA routing — React Router (all routes live in the bundle; each page fetches its own JSON)


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


  <BrowserRouter>
     <Link to="/products">Products</Link>
     <Routes>
         <Route path="/" element={<Home />} />
         <Route path="/products" element={<ProductList />} />
         <Route path="/products/:id" element={<ProductDetail />} />
     </Routes>
  </BrowserRouter>



           RSC routing — Next.js App Router (file-based; each route is a Server Component)


  app/
  ├── layout.jsx                  ← shared shell
  ├── page.jsx                    ← "/"
  └── products/
         ├── page.jsx             ← "/products"                 (async: fetches its data on the server)
         ├── loading.jsx          ← streaming fallback while page.jsx loads
         └── [id]/
             └── page.jsx         ← "/products/5"


  <Link href="/products"> → router fetches that route's RSC payload, merges it



  Stage                 SPA (CSR)                                               RSC (Next.js App Router)

  Initial page          Empty HTML shell + whole JS bundle; React ren‐          Server runs Server Components, fetches data,
  load                  ders in the browser, shows a spinner, then calls        streams HTML + RSC payload; content visible ear‐
                        APIs; content appears last                              ly; small JS hydrates only client components

  Navigation be‐        Client-side router swaps components instantly —         Soft navigation (no full reload): router requests the
  tween pages           no server round trip for the UI, only JSON calls        new route's RSC payload (often prefetched) and
                        for new data                                            merges it, keeping client state

--- PDF page 302 ---
Stage                  SPA (CSR)                                                RSC (Next.js App Router)

  Data fetching          In the browser: useEffect /axios/TanStack                On the server: await inside async components
                         Query to public REST endpoints; loading and er‐          (DB/internal API), secrets safe; writes via Server
                         ror states per component; possible waterfalls            Actions + revalidation

  State                  All in the client: useState , Context + useRe‐           Server data lives on the server (re-rendered,
  management             ducer , Redux; client also caches server data            cached); client state only for interactive bits ( "use
                                                                                  client" components); far less global state



  Criterion          SPA — pros / cons                                           RSC — pros / cons

  Speed              − slow first load (big bundle + waterfall); + very fast     + fast first load, small bundles, streaming; − each
                     once loaded                                                 navigation needs a server round trip

  SEO                − content not in initial HTML; crawlers/link previews       + full HTML for crawlers and social previews
                     may miss it

  Scalability        + static files scale cheaply on a CDN; the API              − server renders per request (needs caching/edge to
                     scales separately; work done on users' devices              scale); + less work on weak devices

  Developer          + simple mental model, any backend, deploy any‐             + data fetching co-located with UI, fewer API end‐
  control            where; full control in the browser; − you build load‐       points; − framework conventions (Next.js),
                     ing/caching/routing glue yourself                           server/client boundary rules, serialization limits,
                                                                                 harder debugging



   PYQ         Final 2025-26 · Q4(B)   ★ LATEST                                                                                     6M


  What are the main differences between a Single-Page Application (SPA) and the newer RSC architec‐
  ture? Explain conceptually how each handles: initial page load; navigation between pages; data
  fetching and state management. Compare pros/cons (speed, SEO, scalability, developer control).

   ✓    MODEL ANSWER — WRITE THIS

  An SPA loads a single HTML page and a JavaScript bundle once, then renders everything in the browser
  (CSR) and talks to the backend only through JSON APIs; routing is client-side (React Router). The RSC ar‐
  chitecture (e.g. Next.js App Router) renders most components on the server as React Server Components,
  sends HTML plus a serialized RSC payload, and ships JavaScript only for interactive "use client"
  components.

                      SPA                                                RSC

    Initial load      Empty HTML + full bundle → render in browser       Server fetches data and streams rendered HTML + RSC pay‐
                      → fetch API → content (spinner first)              load → content immediately; small JS hydrates client parts

    Navigation        Client router swaps components without reload;     Soft navigation: fetches the new route's RSC payload from the
                      only JSON requested                                server (prefetched), merges it, keeps client state

    Data              In the browser via useEffect /axios to pub‐        On the server inside async components (direct DB / internal
    fetching          lic REST endpoints                                 API); mutations via Server Actions

    State             All client-side (useState, Context/Redux) incl.    Server data stays on server; client state only in client
                      cached server data                                 components

--- PDF page 303 ---
Pros/cons. Speed: SPA is slow on first load but very fast afterwards; RSC loads fast with smaller bundles
  and streaming, but each navigation needs a server round trip. SEO: SPA is weak (content not in initial
  HTML); RSC is strong (full HTML). Scalability: SPA scales cheaply — static files on a CDN, the API scales
  separately, rendering happens on users' devices; RSC needs server compute per request and relies on
  caching. Developer control: SPA gives a simple model, any backend and full client control but requires writ‐
  ing loading/caching/API glue; RSC co-locates data fetching with UI and needs fewer API endpoints, but ties
  you to framework conventions and the server/client boundary rules.

  Conclusion: choose an SPA for highly interactive, logged-in apps where SEO does not matter; choose
  RSC for public, content- and data-heavy sites where first-load speed and SEO matter.

  🎯 Marking scheme guess: 1 M definitions · 3 M load / navigation / data & state · 2 M pros-cons on the four criteria


    4.20 Django behind an SPA vs an RSC app
📚 Sources: Not in your files — added from standard references              Builds on: Unit 2 Notes (Django MVT, DRF)       Unit 4 Notes §14–15

 ShopLite React Manual 4.1, 5.2


Django can sit behind a React front end in three ways. The question is always the same: who renders the UI,
and what does Django send?

   A · SPA (Vite + React)
                                  1 · shell + JS
            Browser                                               Static host / CDN                                            Django + DRF
       React renders here                                        index.html + bundle.js                                        public JSON API


                                                   2 · many JSON calls from the browser (CORS + token)

   B · RSC (Next.js App Router)

                               HTML + RSC payload                                                server-to-server JSON
            Browser                                                 Next.js server                                             Django + DRF
        client islands only                                    Server Components render                                       internal JSON API

                                                                                               private network, no CORS


   C · Classic Django MVT (traditional SSR / MPA)

                                  HTML pages
            Browser                                                                        Django views + templates
        full reload per link                                                render(request, "page.html", context) → complete HTML page



                                                       Three ways Django can serve a front end.



▸ A · Django behind an SPA (what ShopLite does)
    Django is a pure API: DRF views/ViewSets return JSON ( Response(serializer.data) / JsonResponse )
    with HTTP status codes (200, 201, 204, 400, 401, 404). No HTML except the browsable API.
    The browser calls Django directly, so Django must send CORS headers ( django-cors-headers ) and au‐
    thenticate each request (token/JWT header or session cookie + CSRF).
    Every piece of data any screen shows needs a public endpoint: lists, details, search, filters, dashboard ag‐
    gregates, auth, CRUD.
    The React build ( dist/ ) is served by nginx/a CDN (or by Django as static files).

--- PDF page 304 ---
▸ B · Django behind an RSC app (Next.js)
      The browser talks to the Next.js server; Server Components call Django server-to-server (e.g.
      http://django:8000/api/ on a Docker network — Unit 5's service-name DNS). Django still returns JSON,
      but to Next.js, not to the browser.
      No CORS needed for those calls (CORS is a browser rule); Django can stay on a private network; API se‐
      crets live in server-only env vars.
      One page can aggregate several Django calls on the server, so endpoints can be fewer, coarser and inter‐
      nal. Mutations go through Server Actions that POST to Django and then revalidate the page.
      Next.js forwards the user's identity (cookie/token) to Django, which still enforces permissions.

            the same data, two consumers


  # Django (both cases) — products/views.py
  class ProductViewSet(viewsets.ModelViewSet):
         queryset = Product.objects.all()
         serializer_class = ProductSerializer                # GET /api/products/ -> JSON list



            consumer 1: browser (SPA) vs consumer 2: Next.js server (RSC)


  // SPA: runs in the user's browser -> cross-origin -> needs CORS + public endpoint
  useEffect(() => { api.get("/products/").then((res) => setProducts(res.data)); }, []);


  // RSC: runs on the Next.js server -> server-to-server -> no CORS, URL can be private
  export default async function Page() {
      const products = await (await fetch("http://django:8000/api/products/")).json();
      return <ProductList products={products} />;
  }


  // RSC mutation: a Server Action posts to Django, then refreshes the page's data
  async function addProduct(formData) {
      "use server";
      await fetch("http://django:8000/api/products/", {
         method: "POST",
         headers: { "Content-Type": "application/json" },
         body: JSON.stringify({
            name: formData.get("name"),
            price: Number(formData.get("price")),
         }),
      });
      revalidatePath("/products");           // from "next/cache": re-render with fresh data
  }

--- PDF page 305 ---
▸ C · Classic Django templates
Django's own MVT is the original server-side rendering: the view queries the model,
 render(request, "products.html", {"products": qs}) fills a template, and Django sends a complete
HTML page; every navigation is a full page reload (an MPA). No React, no separate API needed.

                        SPA                              RSC                                             Django templates

  Who calls             The browser                      The Next.js server                              The browser (page
  Django                                                                                                 requests)

  Django sends          JSON (+ CORS headers, status     JSON to the Next server; Next sends HTML        Full HTML pages
                        codes)                           + RSC payload to the browser

  API endpoints         Most — one public endpoint for   Fewer, internal, page-shaped                    None (views return
  needed                every piece of data                                                              HTML)

  Auth                  Token/JWT header or cookie +     Next forwards the user's cookie/token           Django sessions +
                        CSRF, from the browser                                                           CSRF



   PYQ        Final 2025-26 · Q4(C)   ★ LATEST                                                                        4M


  Describe how a Django backend would interact with each approach (SPA vs RSC). What kind of re‐
  sponses does Django send in each case? Which approach requires more API endpoints?

   ✓     MODEL ANSWER — WRITE THIS

  SPA: Django (with Django REST Framework) acts purely as an API server. The React app running in the
  browser calls it directly (axios/fetch), so Django sends JSON responses with HTTP status codes (200, 201,
  204, 400, 401, 404), plus CORS headers because the frontend is on another origin, and it authenticates
  every request (token/JWT or session + CSRF). The React build itself is served as static files.

  RSC (e.g. Next.js App Router): the browser talks to the Next.js server. Its Server Components (and Server
  Actions) call Django server-to-server over an internal network; Django still returns JSON, but to the Next.js
  server, which turns it into HTML and the RSC payload for the browser. CORS is not needed for these calls,
  Django can stay private, and one page can combine several Django calls on the server. (Classic Django
  templates are a third option: Django itself returns full HTML pages via render() .)

  More endpoints: the SPA. Because all data fetching happens in the browser, every list, detail view, filter,
  search, dashboard figure and form submission needs its own public REST endpoint. In the RSC approach
  data is fetched on the server close to the backend, so endpoints can be fewer, coarser and internal (and
  simple reads can even query the database directly).

               one-line illustration


       SPA:   Browser --GET /api/products/ (CORS, token)--> Django --JSON--> Browser renders
       RSC:   Browser --GET /products--> Next.js server
              Next.js --GET http://django:8000/api/products/--> Django (server-to-server)
              Django --JSON--> Next.js --HTML + RSC payload--> Browser

--- PDF page 306 ---
🎯 Marking scheme guess: 1.5 M SPA interaction + JSON/CORS · 1.5 M RSC interaction (server-to-server JSON) · 1 M SPA needs more
  endpoints, with reason




      4.21 Common mistakes and fixes
📚 Sources: Unit 4 Notes §18       LEC 9 (React) s.24     ShopLite React Manual: Mistakes, Troubleshooting     One-Shot p.16


 Mistake                                         What goes wrong                   Fix

 Mutating state ( arr.push , count++ )           UI does not update                Set a new copy with the setter:
                                                                                    setItems([...items, x])

 Reading state right after setting it            Old value (snapshot)              Compute next in a variable, or react in useEf‐
                                                                                   fect

  setX(x + 1) in timers/async/repeat‐            Lost updates, counter stuck       Functional update setX(prev => prev + 1)
 ed calls

 No key in lists / index as key on a re‐         Warning; wrong or slow re-        Unique, stable id: key={p.id}
 orderable list                                  renders

  onClick={save()}                               Runs during render, not on        Pass the function: onClick={save} or {() =>
                                                 click                             save(id)}

 Missing effect dependency                       Stale data                        List every value the effect uses

 Unstable dependency / effect sets its           Infinite loop                     Primitive deps, move objects inside, use‐
 own dependency                                                                    Memo / useCallback

  useEffect(async () => …)                       Returns a Promise instead of      Define an async function inside and call it
                                                 cleanup

 Hooks inside if or loops                        Hooks get out of order            Call hooks at the top level

 Lowercase component name <card                  Treated as an HTML tag            PascalCase: <Card />
 />

 No error handling on a request                  Blank screen on failure            try / catch / finally + error state + retry

 fetch without res.ok check                      404/500 treated as success         if (!res.ok) throw new Error(…) or use
                                                                                   axios

 Adding the form data instead of res.‐           New item has no id                Append what the server returned
 data

 Prop drilling everywhere                        Messy, fragile code               Context + reducer

 Hard-coded API URL                              Breaks after deployment            VITE_API_URL in .env (restart Vite)

 Secrets in VITE_ variables                      Shipped to every visitor          Keep secrets on the server

 Forgetting CORS / Vite moved to 5174            "Network Error", CORS error       Allow the exact front-end origin in Django; restart
                                                 in Console                        Django after editing .env

 Two requests on load in development             Looks like a bug                  It is <StrictMode> — production runs once

 (RSC) useState in a Server                      Build error                       Move the interactive part into a "use client"
 Component                                                                         component

--- PDF page 307 ---
Mistake                                           What goes wrong                    Fix

 (SSR) Date.now() / window during                  Hydration mismatch                 Read browser-only values in useEffect
 render




      4.22 Likely questions for 2026
📚 Sources: Pattern of all three papers      Unit 4 syllabus line   ShopLite React Manual "Explain it" list


The 2025-26 paper moved from "write a program" to "explain a scenario". Expect both styles. Syllabus words
not yet examined — Context API, Reducer, Provider, Consumer, API handling, backend connectivity — are
the most likely new questions.

  #     Predicted question                                                     Marks        Answer pointer

  1     What is prop drilling? Explain the Context API (createCon‐             10           §4.13 theme example + ShopLite Header
        text, Provider, Consumer, useContext) with a program.                               Consumer; table without/with context

  2     Explain useReducer with an example. Compare with useS‐                 8–10         §4.14 counter reducer, cartReducer ,
        tate. How do Context and Reducer together form a global                              CartProvider , 4-step table
        store?

  3     Write a React component that fetches a list from a Django              10           §4.15 load() with try/catch/finally + the
        REST API showing loading, error and success states.                                 fetch vs axios table; §4.16 for POST/DELETE
        Compare fetch and axios.

  4     A React app on port 5173 cannot read data from Django                  4–6          §4.17: origin, browser-enforced CORS,
        on port 8000. Explain why and give two ways to fix it.                               django-cors-headers settings, Vite
                                                                                            proxy, .env

  5     Explain the component lifecycle (class methods) and map                6–10         §4.4 lifecycle table + ClassCounter; §4.11 ef‐
        each to hooks.                                                                      fect lifecycle

  6     What is the Virtual DOM? Explain reconciliation and why                5            §4.1 diff/patch flow + render/commit; §4.3
        keys are needed in lists.                                                           keys

  7     Short notes: hydration; SSG vs SSR; "use client"; stream‐              2–5          §4.18 vocabulary table, SSG paragraph, RSC
        ing with Suspense.                                                     each         sub-sections

  8     Rules of hooks; write a custom hook (e.g. useFetch ).                  5            §4.10 rules + why (call order); §4.15 use‐
                                                                                            Fetch

  9     Controlled components and forms: build a form that POSTs               6–10         §4.6 controlled input, §4.16
        to an API and shows server validation errors.                                        AddProductForm + errorText

  10    Explain token-based authentication between React and                   6            §4.17 six-step flow, SimpleJWT URLs, inter‐
        Django and a protected route.                                                       ceptor, Protected




      4.23 Last-minute recap
📚 Sources: Unit 4 Notes §19         LEC 9 (React) s.25     One-Shot p.13–16     Complete Revision deck s.30–36, s.45

--- PDF page 308 ---
CORE IDEAS                                                          HOOKS & DATA

        React = library for UIs: component-based, de‐                      Rules of hooks: top level only; only in compo‐
        clarative, Virtual DOM (diff → patch only                          nents/custom hooks (order-based matching).
        changed nodes = reconciliation).                                    useEffect(fn) every render · (fn, [])
        JSX → compiled by Vite/Babel to createEle‐                         once · (fn, [x]) when x changes · return
        ment() ; className , htmlFor , onClick=                            cleanup (before re-run + unmount). Missing
        {fn} , close every tag, one root ( <>…</> ),                       dep = stale; unstable dep = loop.
        {expression} , style={{…}} .                                       Lifecycle map: didMount = [] , didUpdate =
        Component = function returning JSX,                                 [dep] , willUnmount = cleanup.
        PascalCase. Class version: extends                                 Context: createContext → Provider val‐
        React.Component , construc‐                                        ue → useContext / Consumer . Solves prop
        tor / super(props) , this.state ,                                  drilling.
        this.setState (merges), render() .
                                                                           Reducer: pure (state, action) => new‐
        Props: parent → child, read-only, any type;                        State , switch(action.type) , default re‐
        child → parent via callback props.                                 turns state; useReducer(reducer, init) →
        State: owned, changes via setter → re-render;                       [state, dispatch] .
        never mutate; copy arrays/objects.                                 API: fetch in useEffect; loading / error / suc‐
        Snapshot + batching: setX queues; one re-                          cess; finally ; fetch needs res.ok ; axios
        render after the handler (React 18:                                throws + res.data .
        everywhere); new value next render.                                CRUD: GET 200 · POST 201 · PATCH/PUT 200
        Functional update setX(prev => …) when‐                            · DELETE 204 · validation 400; append res.‐
        ever the new value depends on the old: repeat‐                     data .
        ed calls, timers, async, toggles, lists.                           Connectivity: CORS (browser-enforced;
        Lifting state up: shared state in the closest                       django-cors-headers ), VITE_API_URL , Vite
        common parent; alternative = Context.                              proxy; token → Authorization: Bearer .


                   CSR / SPA                                   SSR                             RSC

 Runs              Browser                                     Server + browser (hydrate)      Server only (+ "use client" islands)

 Data              Browser → JSON API                          Server per request              async server components

 Sends             Empty HTML + full JS                        HTML + full JS + data           HTML + RSC payload + client JS

 Speed / SEO       Slow first load, fast after / weak          Fast paint, late TTI / strong   Fast, small JS, streaming / strong

 Django sends      JSON to browser (+CORS), most endpoints     JSON to the render server       JSON server-to-server, fewer endpoints


           skeletons to write from memory


  // state + effect + cleanup
  const [count, setCount] = useState(0);
  useEffect(() => { document.title = `Count: ${count}`; }, [count]);
  useEffect(() => { const id = setInterval(() => setSec((s) => s + 1), 1000);
                           return () => clearInterval(id); }, []);


  // context + reducer

--- PDF page 309 ---
const CartContext = createContext(null);
  function CartProvider({ children }) {
      const [state, dispatch] = useReducer(cartReducer, { items: [] });
      return (
        <CartContext.Provider value={{ state, dispatch }}>{children}</CartContext.Provider>
      );
  }
  const { state, dispatch } = useContext(CartContext);


  // fetch with three states
  async function load() {
      setLoading(true); setError("");
      try { const res = await api.get("/products/"); setProducts(res.data); }
      catch (err) { setError(err.message); }
      finally { setLoading(false); }
  }


  // class component
  class Hello extends React.Component {
      constructor(props) { super(props); this.state = { n: 0 }; }
      componentDidMount() { /* fetch, timers */ }
      componentWillUnmount() { /* cleanup */ }
      inc = () => this.setState((p) => ({ n: p.n + 1 }));
      render() { return <button onClick={this.inc}>{this.state.n}</button>; }
  }


  // RSC (Next.js App Router)
  export default async function Page() {
      const data = await getData();              // server only: DB / Django API
      return <List items={data} />;
  }
  "use client";         // top of an interactive component's file



           commands


  npm create vite@latest app -- --template react
  cd app && npm install && npm run dev         # http://localhost:5173
  npm install axios                 # HTTP client
  npm run build                     # dist/ for production
  pip install django-cors-headers djangorestframework djangorestframework-simplejwt
  python manage.py runserver        # Django REST on :8000