AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 5

    React Fundamentals and Component Architecture

    TechLearningPro's lesson player used to update the outline by reaching into the DOM from three scripts: one for completion checkboxes, one for the note field, and one that rewrote the whole list…

    Course progress0%
    Focus
    18 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 05 · Full-Stack Engineering Foundations

    Lesson Overview

    TechLearningPro's lesson player used to update the outline by reaching into the DOM from three scripts: one for completion checkboxes, one for the note field, and one that rewrote the whole list after a progress poll. During enrollment week the checkbox and the server disagreed. A learner marked "Components" complete, the poll replaced the list, and the checkmark vanished. Support called it a race. The deeper defect was that the screen was not a function of state. It was a pile of mutations with no owner.

    React exists so a user interface can be described as a function of data, then reconciled with the DOM by a runtime that owns the updates. This lesson teaches that model for the lesson player: components, props, state, composition, lists, events, and the boundaries you draw before any data library or framework router arrives. The React course goes wider on the library. Here the goal is the architecture the rest of this course will sit on: a typed React 18 UI that renders learner-visible text safely, fails in a contained way, and can be tested without a browser farm.

    You already have the language pieces. TypeScript for Production Full-Stack Development is how props and state stay honest. Modern JavaScript, Async Programming and Web APIs is how a later fetch will run. This lesson does not fetch yet. It builds the component tree that will receive data. Advanced React, State Management and Data Fetching owns server state. Next.js App Router and Full-Stack React moves the same components onto the server and the client with a written boundary.

    Planning assumptions for the running example, labeled so they are not mistaken for a production capacity plan:

    • The player shows one lesson outline, a short note, and a completion control. It is not the whole platform.
    • Learner notes are plain text, at most a few hundred characters. Model output, when it appears later, is also plain text until a later lesson defines a safer rich format.
    • React 18 with the automatic JSX runtime ("jsx": "react-jsx" in TypeScript). New code uses createRoot from react-dom/client, not the legacy ReactDOM.render.
    • Examples are client UI. Server Components arrive in lesson 7. Do not copy a useState component into a Server Component and expect it to run.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Explain React as a UI runtime that turns a render description into DOM updates, not as a templating string library.
    2. Define a component as a function of props and state, and name which data is owned by which component.
    3. Distinguish props, state, and derived values, and refuse to mirror props into state without a reason.
    4. Compose a lesson shell from smaller components instead of growing one file that both fetches and renders.
    5. Render lists with stable keys tied to identity, and explain what breaks when the key is the array index.
    6. Build controlled form controls whose displayed value lives in React state.
    7. Place an error boundary around a feature so one render failure does not blank the whole player.
    8. Use the React 18 root API and Strict Mode, and explain why development re-runs effects.
    9. Keep learner and model text in normal JSX children so React escapes it, and name dangerouslySetInnerHTML as an exceptional API.
    10. Structure a feature folder with types, presentational components, and a small container.
    11. Test a component by role and accessible name with React Testing Library, not by CSS class.
    12. Sketch the lesson-player tree a staff engineer can extend in lessons 6 through 8 without redrawing ownership.
    13. Hand the next lesson a written rule for what is local UI state versus data that must come from the server.

    Prerequisites

    • You can read TypeScript function components, union types, and ReactNode. The language lesson is the refresher if generics in props feel new.
    • You can read JSX as syntax that becomes JavaScript calls. You do not need to have shipped React.
    • You understand that the browser DOM is mutable and that two writers to the same node will fight. That fight is the problem this lesson removes from application code.
    • Optional: the React course if you want a second pass over hooks after this architecture lands. It is not required to finish the assignment.

    If your team already has components but cannot say who owns the outline array, stay here. The enrollment-week bug returns whenever a new script writes the DOM beside React.

    Detailed Core Concepts

    What a React UI is for

    React's purpose is to let you describe what the screen should show for a given state, then let the library update the DOM to match. The description is a tree of components. A component is a function (or, for a few platform cases, a class) that returns elements. Props are the inputs the parent passes. State is data the component owns and can change over time. When state changes, React calls the component again and compares the new description to the previous one.

    The sentence to memorize is UI = f(state). For the lesson player, "state" at this layer means the outline items, which item is selected, and the note draft. It does not yet mean the HTTP cache. Mixing those too early is how every click starts a fetch.

    React is not the first library to do this, and it is not a backend. It does not authenticate learners, authorize progress writes, or store notes durably. Those stay on the server. React's job is to make the client representation predictable.

    Why the model exists

    Without a single description of the UI, each feature adds another DOM write. The checkbox script sets checked. The poll script rebuilds the list and drops the property. The note script reads textarea.value at the wrong time. Bugs show up as "it worked until the other feature shipped."

    The component model gives you a place to put the source of truth. Parents pass data down as props. Children notify parents through callbacks. That one-way flow is slower to type than a global mutable outline, and it is much faster to debug. You can render the same LessonOutline in a test with a fixture array and assert what the learner would see.

    History, briefly: React popularized this model in the 2010s. React 16 introduced the Fiber reconciler and error boundaries. React 17 moved event delegation to the root and made the JSX transform able to run without import React. React 18, the version this lesson uses, made createRoot the supported entry, added concurrent rendering primitives such as useTransition and useDeferredValue, and made Strict Mode re-run effects in development to expose missing cleanup. You do not need the reconciler's source to use it. You do need to know that render must be pure: no network calls, no DOM writes, no "set state while rendering" as a design.

    Elements, components, and the JSX transform

    A React element is a plain object description: type, props, children. It is not a DOM node. A component is the function that returns elements. JSX is syntax. With TypeScript "jsx": "react-jsx", the compiler uses the automatic runtime and emits imports from react/jsx-runtime. You import react when you use a value such as useState or Component, not merely because a file contains JSX.

    tsx
    function LessonTitle({ title }: { title: string }) {
    return <h1>{title}</h1>;
    }

    <h1>{title}</h1> is not an HTML string concatenated in your function. The text inside {title} is a child, and React assigns it as text content. That distinction matters as soon as a note or a model completion can contain < or an event-handler attribute. Treat it as data.

    Props, state, and derived values

    Props are owned by the parent. A child may read them and should not mutate them. If the child needs to change the outline, it calls onToggle(id) and the parent sets state.

    State is owned by the component that calls useState or useReducer. Put state as low as possible, and lift it when two siblings must stay in sync. The outline and the "3 of 12 complete" summary must share one array, so the array lives in the parent. A dropdown's open flag can live in the dropdown.

    Derived values are computed during render: const completeCount = items.filter((item) => item.complete).length. Do not store completeCount in a second useState and try to keep it updated in an effect. Two sources of truth are the enrollment-week bug in a new costume.

    Composition

    Build the player from small components with narrow props. A shell takes title, children, and optional actions. The outline takes items and onToggle. The note takes value and onChange. The parent composes them. Inheritance of components is the wrong tool; React's composition model is children and props.

    Pass JSX as props when a slot is clearer than children, for example actions={<CompleteButton />}. Keep the slot optional and typed as ReactNode.

    Lists and keys

    React uses keys to match items across renders. The key must be stable for the item's identity and unique among siblings. A lesson id is a key. The array index is a key only when the list is static, never reordered, and never filtered. If you insert an item at the top and key by index, React will reuse the wrong DOM and the wrong component state. The learner sees another lesson's note draft attached to the wrong row.

    Keys are not passed as a normal prop. Do not read props.key inside the child. If the child needs the id, pass id explicitly.

    Events and controlled controls

    React event handlers use camelCase props such as onClick and onChange. The handler receives a synthetic event. You usually read event.target.value for inputs and then store it. A controlled input has its value prop driven by state, so the React state is what the screen shows. An uncontrolled input keeps the value in the DOM and you read it through a ref when you submit. Controlled inputs are the default in this course because validation, character limits, and tests can see the value without poking the DOM.

    Do not mutate the event object or rely on the old event-pooling behavior from React 16. Pooling is gone.

    Render purity and Strict Mode

    The body of a function component must be safe to call more than once. React may render twice in development under Strict Mode, and concurrent features may discard a render. Effects are the place for synchronization with something outside React: a subscription, a timer, a manual DOM measurement. Even then, return a cleanup function.

    Strict Mode does not double-invoke effects in production. If a bug appears only in development, suspect a missing cleanup or a side effect during render before you disable Strict Mode. Disabling it hides the signal.

    Error boundaries

    A rendering error in a child used to unmount the whole tree. An error boundary is a class component that implements static getDerivedStateFromError and optionally componentDidCatch, and renders a fallback. Function components still cannot be error boundaries in React 18. Place a boundary around the outline, not only at the root, so a bad lesson body does not remove the course navigation.

    Error boundaries do not catch errors in event handlers, async code, or server-side failures. Those need their own try/catch and UI state. Lesson 6 shows that for fetches.

    Feature boundaries

    Colocate by feature, not by technical type alone. A components/ folder of 200 unrelated files hides ownership. For the player:

    text
    src/features/lesson-player/
    types.ts
    LessonPlayer.tsx
    LessonOutline.tsx
    LessonNote.tsx
    LessonErrorBoundary.tsx
    LessonOutline.test.tsx

    Presentational components receive data and callbacks. The container owns state. Neither file calls fetch in this lesson. When lesson 6 adds a query, it should sit beside the container, not inside LessonOutline, so the outline stays usable in tests and in a Storybook-style fixture if you add one later.

    Architecture and Design Diagrams

    The player is a client tree. The server is drawn so you remember it exists, and so you do not pretend a checkbox is durable.

    flowchart TB
      subgraph browser [Browser]
        Root[createRoot and StrictMode]
        Player[LessonPlayer state owner]
        Outline[LessonOutline]
        Note[LessonNote]
        Boundary[LessonErrorBoundary]
      end
    
      subgraph later [Later lessons]
        API[Progress API on the server]
      end
    
      Root --> Boundary
      Boundary --> Player
      Player --> Outline
      Player --> Note
      Player -. "callbacks only in this lesson" .-> Outline
      API -. "lesson 6 reads and writes" .-> Player

    One-way data flow inside the player:

    text
    LessonPlayer state
    | props: items, note, callbacks
    v
    LessonOutline / LessonNote
    | events: onToggle(id), onChange(text)
    v
    LessonPlayer setState
    |
    v
    React render -> DOM

    Trust boundary: anything rendered on the client can be read and modified by the learner. Completion posted later must be checked on the server against the session. The component tree is not an authorization boundary. Lesson 7 and the security module make that operational. This lesson only forbids hiding privileged decisions inside a component that runs in the browser.

    Technical Explanation

    What happens when the learner toggles a row:

    1. The browser fires a click on the checkbox.
    2. React calls the onChange handler you passed.
    3. The handler calls the parent's onToggle(id).
    4. The parent computes the next array with map and passes it to setItems. State updates are not mutations of the previous array.
    5. React schedules a render of LessonPlayer and its children.
    6. LessonOutline returns a list of elements. React reconciles that list with the previous list using keys.
    7. The DOM checkbox for that id updates. Siblings with the same id and same props can be skipped when their description did not change. You do not code that skip by hand.

    What happens on a render throw:

    1. A child throws during render.
    2. The nearest error boundary's getDerivedStateFromError returns fallback state.
    3. React renders the fallback in place of the children.
    4. componentDidCatch runs so you can log a non-sensitive diagnostic. Do not log the note text, the lesson body, or anything that looks like a token.

    What you must not do during render: call fetch, write localStorage, or call setState unconditionally. Those belong in handlers or effects, and effects that fetch belong to the next lesson's pattern with cancellation.

    Practical Implementation

    Stack for the snippets: React 18, TypeScript, automatic JSX runtime. No new dependencies beyond react, react-dom, and the test packages named in the testing section.

    Simple example: a typed presentational title

    tsx
    // src/features/lesson-player/LessonTitle.tsx
    type LessonTitleProps = {
    title: string;
    moduleLabel: string;
    };
    export function LessonTitle({ title, moduleLabel }: LessonTitleProps) {
    return (
    <header>
    <p>{moduleLabel}</p>
    <h1>{title}</h1>
    </header>
    );
    }

    The title is text, not HTML. If a catalog bug ever stored markup in title, the learner would see the characters, not an injected element.

    Intermediate example: controlled note and lifted outline state

    tsx
    // src/features/lesson-player/types.ts
    export type OutlineItem = {
    id: string;
    title: string;
    complete: boolean;
    };
    // src/features/lesson-player/LessonNote.tsx
    type LessonNoteProps = {
    value: string;
    onChange: (next: string) => void;
    };
    const NOTE_LIMIT = 500;
    export function LessonNote({ value, onChange }: LessonNoteProps) {
    const remaining = NOTE_LIMIT - value.length;
    return (
    <label>
    Lesson note
    <textarea
    value={value}
    maxLength={NOTE_LIMIT}
    onChange={(event) => onChange(event.target.value)}
    />
    <span>{remaining} characters left</span>
    </label>
    );
    }
    tsx
    // src/features/lesson-player/LessonOutline.tsx
    import type { OutlineItem } from "./types";
    type LessonOutlineProps = {
    items: readonly OutlineItem[];
    onToggle: (id: string) => void;
    };
    export function LessonOutline({ items, onToggle }: LessonOutlineProps) {
    const completeCount = items.filter((item) => item.complete).length;
    return (
    <section aria-label="Lesson outline">
    <p>
    {completeCount} of {items.length} complete
    </p>
    <ul>
    {items.map((item) => (
    <li key={item.id}>
    <label>
    <input
    type="checkbox"
    checked={item.complete}
    onChange={() => onToggle(item.id)}
    />
    {item.title}
    </label>
    </li>
    ))}
    </ul>
    </section>
    );
    }

    completeCount is derived. The checkbox is controlled by item.complete. The label wraps the input so the accessible name is the lesson title.

    Enterprise example: container, boundary, and root

    tsx
    // src/features/lesson-player/LessonPlayer.tsx
    import { useState } from "react";
    import { LessonNote } from "./LessonNote";
    import { LessonOutline } from "./LessonOutline";
    import { LessonTitle } from "./LessonTitle";
    import type { OutlineItem } from "./types";
    type LessonPlayerProps = {
    moduleLabel: string;
    title: string;
    initialItems: readonly OutlineItem[];
    };
    export function LessonPlayer({ moduleLabel, title, initialItems }: LessonPlayerProps) {
    const [items, setItems] = useState(initialItems);
    const [note, setNote] = useState("");
    function toggle(id: string) {
    setItems((current) =>
    current.map((item) =>
    item.id === id ? { ...item, complete: !item.complete } : item,
    ),
    );
    }
    return (
    <article>
    <LessonTitle moduleLabel={moduleLabel} title={title} />
    <LessonOutline items={items} onToggle={toggle} />
    <LessonNote value={note} onChange={setNote} />
    </article>
    );
    }

    Use the functional updater form of setItems so two quick toggles do not drop one update. Copy the item you change. Do not item.complete = !item.complete on the existing object.

    tsx
    // src/features/lesson-player/LessonErrorBoundary.tsx
    import { Component, type ErrorInfo, type ReactNode } from "react";
    type Props = { children: ReactNode; fallback: ReactNode };
    type State = { hasError: boolean };
    export class LessonErrorBoundary extends Component<Props, State> {
    state: State = { hasError: false };
    static getDerivedStateFromError(): State {
    return { hasError: true };
    }
    componentDidCatch(error: Error, info: ErrorInfo): void {
    // Names only. Do not log note text, lesson bodies, or secrets.
    console.error("lesson_player_render_failed", {
    name: error.name,
    componentStack: info.componentStack,
    });
    }
    render(): ReactNode {
    if (this.state.hasError) return this.props.fallback;
    return this.props.children;
    }
    }
    tsx
    // src/main.tsx
    import { StrictMode } from "react";
    import { createRoot } from "react-dom/client";
    import { LessonErrorBoundary } from "./features/lesson-player/LessonErrorBoundary";
    import { LessonPlayer } from "./features/lesson-player/LessonPlayer";
    const rootElement = document.getElementById("root");
    if (!rootElement) {
    throw new Error("Missing #root element");
    }
    const initialItems = [
    { id: "react-components", title: "Components", complete: false },
    { id: "props-and-state", title: "Props and state", complete: false },
    ];
    createRoot(rootElement).render(
    <StrictMode>
    <LessonErrorBoundary fallback={<p>The lesson player failed to render.</p>}>
    <LessonPlayer
    moduleLabel="Full-Stack Engineering Foundations"
    title="React Fundamentals and Component Architecture"
    initialItems={initialItems}
    />
    </LessonErrorBoundary>
    </StrictMode>,
    );

    This fixture is local data for the lesson. It is not a progress API. Lesson 6 replaces initialItems as the long-term source of truth with a query, and keeps this component able to render from props so tests stay fast.

    Security

    React's default text rendering is the control that stops most reflected markup in this UI. {note} and {item.title} become text nodes. The API that opts out is dangerouslySetInnerHTML, and the name is intentional. Do not use it for lesson notes, catalog titles, or model completions. If a future lesson needs formatted content, it needs a reviewed sanitizer and a defined subset of markup, not a string injected because the model returned HTML.

    The component tree runs on the learner's machine. Hiding a button is not authorization. A disabled checkbox does not stop a forged request. When lesson 6 posts completion, the server must decide whether this session may mark that lesson. Design the props so the client displays the server's answer rather than inventing a role check that only exists in JavaScript.

    Do not put secrets in the player: no API keys in source, no tokens in localStorage as a shortcut, no lesson body logged from componentDidCatch. Error logs in this lesson carry error.name and the component stack.

    Third-party components are supply chain. Pin versions, review what they render, and do not give a widget raw learner HTML. The Next.js course and lesson 7 add the server boundary; they do not relax this rule.

    Testing

    Test behavior through accessible roles. The outline's checkbox name is the lesson title because the input sits inside a label. That is the same contract a screen reader uses, and lesson 8 will hold you to it.

    tsx
    // src/features/lesson-player/LessonOutline.test.tsx
    import { render, screen } from "@testing-library/react";
    import userEvent from "@testing-library/user-event";
    import { describe, expect, it, vi } from "vitest";
    import { LessonOutline } from "./LessonOutline";
    describe("LessonOutline", () => {
    it("toggles by lesson id", async () => {
    const user = userEvent.setup();
    const onToggle = vi.fn();
    render(
    <LessonOutline
    items={[{ id: "react-components", title: "Components", complete: false }]}
    onToggle={onToggle}
    />,
    );
    await user.click(screen.getByRole("checkbox", { name: "Components" }));
    expect(onToggle).toHaveBeenCalledWith("react-components");
    });
    it("derives the complete count from items", () => {
    render(
    <LessonOutline
    items={[
    { id: "a", title: "One", complete: true },
    { id: "b", title: "Two", complete: false },
    ]}
    onToggle={vi.fn()}
    />,
    );
    expect(screen.getByText("1 of 2 complete")).toBeTruthy();
    });
    });

    Also test the container's reducer-like update if you extract toggle logic: given two items, toggling one id flips only that id and does not mutate the previous array. A render test that clicks twice should end with both updates applied, which is why the functional setItems form matters.

    Failure path: render LessonErrorBoundary around a child that throws, and expect the fallback text. Do not assert on console.error text that includes learner content, because the boundary is specified not to log it.

    Run with your existing Vitest setup. @testing-library/react and @testing-library/user-event are the libraries these imports use. If vi is unfamiliar, it is Vitest's mock function; Jest's equivalent is jest.fn() with the same assertion shape.

    Performance

    Render cost for this player is small. The habits still matter when the outline becomes a course tree:

    • Keep list items cheap and keyed. Unkeyed lists and index keys cause extra DOM work and state bugs that look like slowness.
    • Derive counts during render. An effect that copies props into state renders twice and drifts.
    • React.memo, useMemo, and useCallback are tools after a measured problem. Wrapping every row "just in case" adds comparison work and noise. The React Compiler, if your toolchain enables it, changes the tradeoff. Check the React version in the repo before sprinkling memoization.
    • Do not fetch inside the outline. A list that fetches per row is a waterfall you will debug in production. The parent, or the server component in lesson 7, loads data once.
    • Strict Mode's extra development render is not a production performance bug. Do not "fix" it by removing Strict Mode.
    • Pass stable ids, not freshly created objects, when a child is memoized. Inline items={[{...}]} in a parent that re-renders will look like a new list every time.

    Use React Developer Tools Profiler when a screen is actually slow. Guessing is how useMemo spreads through a codebase that was fine.

    Enterprise Real-World Scenarios

    Scenario A: The poll that wiped the checkbox

    Two writers updated completion: local click and a full-list innerHTML refresh. Learners reported lost progress that the server sometimes had and sometimes did not.

    What good looks like. One items state, updated immutably, rendered by LessonOutline. A later query updates that state in one place. No feature writes DOM nodes the outline also owns.

    Scenario B: Index keys and the wrong note

    The team keyed rows by index and stored a draft note inside each row component. Reordering the outline attached the draft to a different lesson.

    What good looks like. Key by lesson id. Lift the draft to the player keyed by the selected id, or store drafts in a map from id to string. Reorder tests are part of the suite.

    Scenario C: Model HTML in the title slot

    An experiment rendered a model "summary" with dangerouslySetInnerHTML because the model returned markdown-looking HTML. A crafted lesson title, if it ever flowed through that slot, would run as markup.

    What good looks like. Model output is text, rendered as a child. Formatting is a separate, reviewed pipeline. The AI module owns grounding and prompts; this lesson owns the rule that the player does not interpret model text as HTML.

    Scenario D: One root boundary

    A single boundary wrapped the app. A throw in the outline removed navigation, so learners could not leave the broken lesson.

    What good looks like. A boundary around the player feature with a fallback that keeps the shell. Event-handler failures still set an error state; the boundary is not a global try/catch.

    Scenario E: Props copied into state

    useState(items) initialized from props and never updated when the parent refetched. The UI showed the first payload forever.

    What good looks like. Either the parent owns state and passes items down, or the child derives from props. Duplicating props into state requires a deliberate reset policy, not an accident of the initial render.

    Best Practices

    1. Write the state ownership sentence before adding a component: who holds the outline, who may change it, and what is derived.
    2. Keep function component bodies pure. Side effects go in handlers or effects.
    3. Update state immutably, and prefer functional updates when the next value depends on the previous one.
    4. Key lists by stable domain ids.
    5. Control form fields that you validate or limit.
    6. Compose with children and typed slots instead of component inheritance.
    7. Colocate a feature's components, types, and tests.
    8. Put error boundaries on feature seams and log only non-sensitive diagnostics.
    9. Render untrusted text as children, not as HTML.
    10. Start new apps with createRoot and Strict Mode.
    11. Type props. Avoid any on onToggle and item shapes; the language lesson already paid for that.
    12. Test through roles and names so the test tracks the accessibility contract.
    13. Lift state only when two consumers must share it. Do not lift everything to the root "for architecture."
    14. Leave data fetching out of presentational components.
    15. Treat client checks as UX. Authorization stays on the server.
    16. Read current React docs when a hook's signature is in question. This lesson uses stable React 18 APIs only.
    17. Do not disable Strict Mode to silence double effects. Fix the cleanup.
    18. Keep the public component API small: data in, events out.
    19. Prefer semantic elements (button, label, ul) even before lesson 8's full pass.
    20. When a design needs dangerouslySetInnerHTML, stop and review it as a security change.

    Common Mistakes and Anti-Patterns

    1. Mutating state. Symptom: the UI sometimes updates, sometimes not. Cause: item.complete = true on an object already in state. Fix: copy the object and the array.
    2. Index keys on a changing list. Symptom: drafts or input focus jump rows. Cause: React matched by position. Fix: key by id and add a reorder test.
    3. Side effects during render. Symptom: double fetches or crashes under Strict Mode. Cause: fetch or setState in the component body. Fix: event handler or effect with cleanup. Fetch patterns are lesson 6.
    4. Duplicated derived state. Symptom: the count disagrees with the checkboxes. Cause: a second useState updated by hand. Fix: compute during render.
    5. Using ReactDOM.render in a React 18 app. Symptom: warnings and no concurrent features. Cause: a copied snippet. Fix: createRoot from react-dom/client.
    6. Error boundary as a function. Symptom: the boundary never catches. Cause: React 18 only supports class boundaries. Fix: the class component in this lesson.
    7. Logging learner content from componentDidCatch. Symptom: notes show up in log drains. Cause: logging error.message or props blindly. Fix: log error.name and a stable feature code.
    8. dangerouslySetInnerHTML for model text. Symptom: markup executes if the string is hostile. Cause: treating HTML as a display format. Fix: text children.
    9. Giant LessonPlayer.tsx that fetches, formats, and renders. Symptom: tests need a network. Cause: no presentational seam. Fix: the folder split in this lesson.
    10. Client-only "admin" props. Symptom: a hidden button still calls an API that trusts the browser. Cause: UI treated as a trust boundary. Fix: server authorization in later lessons; do not add the privileged call here.

    Knowledge Check

    1. What problem does a component architecture solve for the lesson player?

    It gives the outline one source of truth and a pure description of the UI, so completion, notes, and summaries cannot each write the DOM independently. The enrollment-week bug was two writers. React replaces that with props down, events up, and reconciliation.

    2. What alternatives exist, and when would you choose each?

    Direct DOM or jQuery-style updates fit a tiny static page and become a liability as soon as two features share nodes. A template library that re-renders a string can work, but you still need a state owner and an escaping story. React fits this course because the same components move into Next.js in lesson 7 and the React course and Next.js course share the model. Choose uncontrolled inputs only for throwaway fields you read on submit. Choose controlled inputs for anything you validate, limit, or test.

    3. Which data and trust boundaries matter?

    The parent owns outline state in this lesson. Props are read-only to the child. The browser is untrusted: rendered UI is not authorization, and text from learners or models is untrusted content that must stay text. Durable progress is a server concern. Secrets do not belong in the client bundle.

    4. What can fail, and how should the system respond?

    A child can throw during render; the feature error boundary shows a fallback and logs a non-sensitive diagnostic. Event handlers and later fetches are outside the boundary and need explicit error state. A bad key causes crossed state; tests should reorder the list. Strict Mode can reveal a side effect during render; fix the purity issue.

    5. How would you test this?

    Render LessonOutline with a fixture, click the checkbox by its accessible name, and assert onToggle received the lesson id. Assert the derived count. Assert that an updater does not mutate the previous array. Render a throwing child inside LessonErrorBoundary and expect the fallback. No network is required for this lesson's tests.

    Interview Questions and Answers

    Q1. What does "UI = f(state)" mean in React?

    The screen is the result of calling your components with the current props and state. You do not keep a parallel copy of the UI in hand-written DOM calls. When state changes, React renders again and updates the DOM to match the new description.

    Q2. Why must state updates be immutable?

    React compares old and new references and uses that model to decide what to update. In-place mutation can leave the reference unchanged, so the UI skips an update, or it can corrupt memoized children. Copy the pieces you change.

    Q3. When do you lift state?

    When two children must stay consistent, such as the outline and the complete count, or the selected lesson and the note keyed to it. If only one component cares, leave the state there. Lifting everything to the root recreates a global mutable bag.

    Q4. Why are index keys dangerous?

    They name a position, not an item. Inserting, deleting, or reordering makes React associate component state and DOM with the wrong item. Use a stable id from the domain.

    Q5. What is an error boundary, and what does it miss?

    A class component that catches render errors in its children and shows a fallback. It does not catch event-handler errors, async errors, or errors in the boundary itself. Those need local handling.

    Q6. How does React 18 expect you to mount an app?

    createRoot from react-dom/client, then root.render. The legacy ReactDOM.render API is not the React 18 path. Strict Mode wraps the tree in development to highlight unsafe side effects.

    Q7. Why does Strict Mode run effects twice in development?

    To surface missing cleanup. React mounts, unmounts, and remounts the effect in development. Production does not do that extra cycle. The fix is a correct cleanup function, not a disabled Strict Mode.

    Q8. Controlled versus uncontrolled inputs?

    A controlled input's value lives in React state and the value prop. An uncontrolled input keeps the value in the DOM until you read a ref. This course defaults to controlled fields so limits, validation, and tests share one value.

    Q9. How does React reduce XSS risk by default, and where does that stop?

    Text children are escaped as text content. The risk returns if you use dangerouslySetInnerHTML, inject scripts through a poorly reviewed dependency, or treat the client as the place that enforces authorization. Escaping is necessary and not sufficient.

    Q10. What belongs in a presentational component versus a container?

    Presentational components take props and emit callbacks so they render in tests with fixtures. Containers own state and, later, wiring to queries. The split is about testability and reuse, not about a mandatory folder taxonomy.

    Q11. Why can't a function component be an error boundary in React 18?

    The boundary API is getDerivedStateFromError and componentDidCatch on a class. That is the supported mechanism in React 18. Check the React docs for your major version before assuming a newer API exists.

    Q12. How would you review a PR that stores props in useState?

    Ask what should happen when the prop changes. If the answer is "the UI should follow the prop," delete the state and render the prop. If the answer is "this is a draft that starts from the prop," define the reset rule explicitly and test it. Accidental copies go stale.

    Assignment

    Problem. Build the TechLearningPro lesson-player feature from this lesson: typed outline items, a controlled note, lifted state, stable keys, an error boundary, and tests. No network calls.

    Tasks.

    1. Create the feature folder and the types, outline, note, player, and error boundary modules. Match the ownership rules above.
    2. Seed three outline items with string ids. Toggling one must not change the others or mutate the previous array.
    3. Cap the note at 500 characters and show the remaining count as derived state.
    4. Add a reorder control or a test that reverses the items and proves the note draft stays with the selected lesson id, not the visual index. If the note is a single field for the page, document that choice and still key the list by id.
    5. Wrap the player in LessonErrorBoundary. Include a test where a child throws and the fallback renders.
    6. Add the Testing Library tests for toggle-by-id and the derived count.
    7. Write ten lines on trust: what the client displays, what it must not authorize, and why titles render as text.

    Deliverable. Source with no secrets, test output, a one-page component diagram (the Mermaid in this lesson is a valid start), and the trust note.

    Challenge. A second tenant's outline arrives as a new initialItems prop after first render. Show whether your player keeps the old array, and change the design so a changed lesson id resets local drafts without a refresh. Explain why a silent useState(initialItems) fails that case.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security and privacy (text rendering, log hygiene, no client-side authorization story) 20%. Testing and the failure path 20%. Documentation and the ownership write-up 15%.

    Lesson Summary

    React gives TechLearningPro a single description of the lesson player: components in, DOM updates out, props down, events up. State lives in the owner, derived values are computed, lists are keyed by identity, and a class error boundary keeps one feature from blanking the shell. Text stays text. The client remains outside the authorization boundary.

    Advanced React, State Management and Data Fetching takes this tree and separates local UI state from server state, with cancellation and tests for failure. Next.js App Router and Full-Stack React then decides which of these components can run on the server. The React course is the parallel deep dive if you want more hook surface after the assignment.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.