Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 03 / Stage 1

State and events

Goal: Tell state apart from props, use useState correctly - including why mutating a value directly never updates the screen - wire up onClick/onChange handlers the right way, use an updater function when the next value depends on the last, lift shared state up to a common parent, and see the difference between a controlled and an uncontrolled input. Time: ~5 hours · Level: comfortable with modern JS and HTML, finished Parts 1–2

What you will learn

  • How state (a component's own, self-updatable value) is different from props (a value only a parent can change) - and why a component that needs to change something it displays always needs state for it
  • useState's one real job: giving React a way to find out a value changed, so it knows to re-render
  • onClick and onChange - passing a handler reference to React versus calling it by accident, and the exact crash that second mistake produces
  • Why mutating state directly (.push(), array[0] = ...) does nothing visible, even though the value really did change underneath
  • Updater functions (setCount(c => c + 1)) for the one case where the next value depends on the one before it, and the stale-value bug they fix
  • Lifting state up: moving a value to the closest shared parent of every sibling that needs it, instead of duplicating it
  • Controlled vs. uncontrolled inputs, as an introduction - who holds the current value while you type, nothing about reading an uncontrolled field yet (Part 5's job)
  • This part's running examples: a step badge and click counter, a greeting form for a visitor, a tiffin-shop cart, a triple-add button, a restaurant search panel, and a promo code field

A note on how this part is organised: same convention as Parts 1–2 - every examples/ and solutions/ file here is wired into this repo's own harness/ and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.

Topics in this part

Practice

Every exercise below is a React component or pair of components (.jsx), each paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course.


Exercise 1: A component that owns its own toggle state

Scenario: A Flipkart-style product card needs a wishlist heart that the shopper can turn on and off, with nothing from outside the component involved. What to do: Write WishlistButton() with its own useState, starting at false. Clicking the button toggles that state. Render "♡ Add to wishlist" while it is false, "♥ Wishlisted" while it is true.

Sample output (really run, @testing-library/user-event):

initial render       -> "♡ Add to wishlist"
click the button once -> "♥ Wishlisted"
click the button again -> "♡ Add to wishlist"

💡 Hint: setIsWishlisted((current) => !current) inside the button's onClick - this part's ClickCounter is the same shape (one piece of state, one button, one setter call per click), just toggling a boolean instead of incrementing a number.


Exercise 2: Wire up onChange and onClick correctly

Scenario: A Zomato-style delivery feedback box needs a comment field and a submit button, the same two event types this part's GreetingForm already wired up for a name field. What to do: Write DeliveryFeedbackForm() with a comment piece of state updated via onChange, and a "Submit feedback" button that, on click, shows a thank-you message built from the current comment - or a generic one if the comment is blank.

Sample output (both really rendered and interacted with):

type "Rider was late" into the comment field, click "Submit feedback"
→ "Thanks for your feedback: Rider was late"

leave the comment field blank, click "Submit feedback"
→ "Thanks for your feedback!"

💡 Hint: this is GreetingForm's exact shape - an onChange handler that calls a setter with event.target.value, and a separate onClick handler (passed as a reference, never called with parentheses) that reads the current state and sets a second piece of state from it.


Exercise 3: Find and fix a direct-mutation bug

Scenario: A Myntra-style wishlist screen adds items with this helper, wired to an "Add to wishlist" button:

function addItemBroken(name) {
  wishlist.push(name);
}

Testers report the "items in wishlist" count never changes, no matter how many times they click "Add to wishlist" - even though re-opening the wishlist later (a separate bug fix, not part of this exercise) does show the items are actually there. What to do: Write both WishlistCountBroken (using the helper above, unchanged) and WishlistCountFixed, where only the fixed version's add function actually calls its state setter with a new array. Both start from an empty wishlist and add "Kurta - Blue" on a click.

Sample output (really run, two clicks on each):

WishlistCountBroken: "Items in wishlist: 0" (stuck, even after two clicks)
WishlistCountFixed:  "Items in wishlist: 1" after one click, "Items in wishlist: 2" after two

💡 Hint: this part's CartBroken/CartFixed (section 4) is this exact bug and fix, renamed - setWishlist([...wishlist, name]) instead of wishlist.push(name).


Exercise 4: Fix a stale-value bug with an updater function

Scenario: A Zomato-style cart has a "+5" quick-add button on one item, meant to add 5 to that item's quantity in one click. A teammate wrote:

function addFiveBroken() {
  setQuantity(quantity + 1);
  setQuantity(quantity + 1);
  setQuantity(quantity + 1);
  setQuantity(quantity + 1);
  setQuantity(quantity + 1);
}

What to do: Write both QuantityStepperBroken (using the handler above, unchanged) and QuantityStepperFixed, where the fixed version's "+5" handler uses an updater function so all five calls really stack.

Sample output (really run, one click on "+5" on each, starting from a quantity of 1):

QuantityStepperBroken: "Quantity: 2"  (moved by 1, not 5)
QuantityStepperFixed:  "Quantity: 6"  (moved by 5, as intended)

💡 Hint: this part's TripleAddBroken/TripleAddFixed (section 5) is this exact bug, just five calls instead of three - setQuantity((current) => current + 1), five times.


Exercise 5: Lift shared state up to a common parent

Scenario: An IRCTC-style train search screen has a city filter box and a sibling "results count" readout, built - on purpose, for this exercise - the broken way first: each sibling keeps its own, disconnected useState for the selected city. What to do: Write CityFilterPanelBroken (two siblings, each with its own local city state - typing in the filter box never reaches the sibling readout) and CityFilterPanelFixed (the city state lifted to the shared parent, passed down to both siblings as a value and a setter). Both siblings should keep the exact same component names and props shape as this part's SearchBoxFixed/ResultsSummaryFixed, renamed for trains.

Sample output (really run, type "Pune" into the filter box in each panel):

CityFilterPanelBroken: filter box shows "Pune", sibling readout still reads
                        "Showing all trains" (never updated)

CityFilterPanelFixed:  filter box shows "Pune", sibling readout now reads
                        'Showing trains to "Pune"'

💡 Hint: this part's RestaurantSearchPanelBroken/RestaurantSearchPanelFixed (section 6) is this exact shape, renamed for a train search instead of a restaurant search - the only two things that should change are the domain text and the component names.


Exercise 6: Build a controlled and an uncontrolled version of the same field

Scenario: An e-commerce checkout page needs a coupon code field. The team wants to see, side by side, what changes in behavior between a controlled version (React state as the source of truth) and an uncontrolled one (the DOM holding the value) before deciding which one the real checkout form should use. What to do: Write CouponFieldControlled (a value + onChange input backed by useState, with a paragraph underneath showing what React's own state currently holds) and CouponFieldUncontrolled (a defaultValue-only input, with a paragraph underneath that is static text, not derived from any state).

Sample output (really run, type "save20" into each field):

CouponFieldControlled:   input shows "SAVE20" (onChange upper-cased it)
                          paragraph shows "React's own state for this field: SAVE20"

CouponFieldUncontrolled: input shows "save20" (the DOM node held it, untouched)
                          paragraph is unchanged: "React does not track this field's current value at all."

💡 Hint: this is examples/06_controlled_vs_uncontrolled.jsx's exact pair, renamed for a coupon field - PromoCodeControlled/PromoCodeUncontrolled already show the whole shape, including the upper-casing in onChange that makes the controlled/uncontrolled difference easy to see in the rendered input itself.

Show the solutions for Part 3 (12 files)

solutions/ex01_wishlist_button.jsx

// Exercise 1 solution: one piece of state, one button, one setter call per
// click - the same shape as the lesson's ClickCounter (section 1), toggling
// a boolean instead of incrementing a number.

import { useState } from "react";

export function WishlistButton() {
  const [isWishlisted, setIsWishlisted] = useState(false);

  return (
    <button onClick={() => setIsWishlisted((current) => !current)}>
      {isWishlisted ? "♥ Wishlisted" : "♡ Add to wishlist"}
    </button>
  );
}

solutions/ex01_wishlist_button.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { WishlistButton } from "./ex01_wishlist_button.jsx";

describe("WishlistButton toggles its own state on each click", () => {
  it("starts unwishlisted and flips on every click", async () => {
    const user = userEvent.setup();
    render(<WishlistButton />);

    expect(screen.getByRole("button", { name: "♡ Add to wishlist" })).toBeInTheDocument();

    await user.click(screen.getByRole("button"));
    expect(screen.getByRole("button", { name: "♥ Wishlisted" })).toBeInTheDocument();

    await user.click(screen.getByRole("button"));
    expect(screen.getByRole("button", { name: "♡ Add to wishlist" })).toBeInTheDocument();
  });
});

solutions/ex02_delivery_feedback_form.jsx

// Exercise 2 solution: the lesson's GreetingForm shape (section 3) - an
// onChange handler that updates one piece of state from the event, and a
// separate onClick handler (passed by reference, never called) that reads
// the current state and sets a second piece of state from it.

import { useState } from "react";

export function DeliveryFeedbackForm() {
  const [comment, setComment] = useState("");
  const [thankYouMessage, setThankYouMessage] = useState("");

  function handleCommentChange(event) {
    setComment(event.target.value);
  }

  function handleSubmitClick() {
    setThankYouMessage(comment.trim() ? `Thanks for your feedback: ${comment}` : "Thanks for your feedback!");
  }

  return (
    <div className="delivery-feedback-form">
      <label htmlFor="delivery-comment">Comment</label>
      <input id="delivery-comment" value={comment} onChange={handleCommentChange} />
      <button onClick={handleSubmitClick}>Submit feedback</button>
      {thankYouMessage && <p>{thankYouMessage}</p>}
    </div>
  );
}

solutions/ex02_delivery_feedback_form.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { DeliveryFeedbackForm } from "./ex02_delivery_feedback_form.jsx";

describe("DeliveryFeedbackForm wires onChange and onClick correctly", () => {
  it("thanks the user by comment text on submit", async () => {
    const user = userEvent.setup();
    render(<DeliveryFeedbackForm />);

    await user.type(screen.getByLabelText("Comment"), "Rider was late");
    await user.click(screen.getByRole("button", { name: "Submit feedback" }));

    expect(screen.getByText("Thanks for your feedback: Rider was late")).toBeInTheDocument();
  });

  it("falls back to a generic thank-you when the comment is left blank", async () => {
    const user = userEvent.setup();
    render(<DeliveryFeedbackForm />);

    await user.click(screen.getByRole("button", { name: "Submit feedback" }));

    expect(screen.getByText("Thanks for your feedback!")).toBeInTheDocument();
  });
});

solutions/ex03_wishlist_count.jsx

// Exercise 3 solution: the lesson's CartBroken/CartFixed bug and fix
// (section 4), renamed for a wishlist. The broken version's add function
// mutates the same array useState holds, in place, and never calls the
// setter - the array really does grow, but React never re-renders because
// it was never told anything changed.

import { useState } from "react";

export function WishlistCountBroken() {
  const [wishlist, setWishlist] = useState([]);

  function addItemBroken(name) {
    wishlist.push(name);
  }

  return (
    <div>
      <p>Items in wishlist: {wishlist.length}</p>
      <button onClick={() => addItemBroken("Kurta - Blue")}>Add to wishlist</button>
    </div>
  );
}

export function WishlistCountFixed() {
  const [wishlist, setWishlist] = useState([]);

  function addItemFixed(name) {
    setWishlist([...wishlist, name]);
  }

  return (
    <div>
      <p>Items in wishlist: {wishlist.length}</p>
      <button onClick={() => addItemFixed("Kurta - Blue")}>Add to wishlist</button>
    </div>
  );
}

solutions/ex03_wishlist_count.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { WishlistCountBroken, WishlistCountFixed } from "./ex03_wishlist_count.jsx";

describe("WishlistCountBroken: mutating state directly does nothing on screen", () => {
  it("stays stuck at 0 no matter how many times you click", async () => {
    const user = userEvent.setup();
    render(<WishlistCountBroken />);

    expect(screen.getByText("Items in wishlist: 0")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "Add to wishlist" }));
    await user.click(screen.getByRole("button", { name: "Add to wishlist" }));

    expect(screen.getByText("Items in wishlist: 0")).toBeInTheDocument();
  });
});

describe("WishlistCountFixed: a new array reference triggers a real re-render", () => {
  it("increases by one on every click", async () => {
    const user = userEvent.setup();
    render(<WishlistCountFixed />);

    await user.click(screen.getByRole("button", { name: "Add to wishlist" }));
    expect(screen.getByText("Items in wishlist: 1")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "Add to wishlist" }));
    expect(screen.getByText("Items in wishlist: 2")).toBeInTheDocument();
  });
});

solutions/ex04_quantity_stepper.jsx

// Exercise 4 solution: the lesson's TripleAddBroken/TripleAddFixed bug and
// fix (section 5), stretched to five calls instead of three. The broken
// handler calls setQuantity five times with the same stale "quantity + 1"
// expression; the fixed handler passes an updater function each time, so
// every call really builds on the one before it.

import { useState } from "react";

export function QuantityStepperBroken() {
  const [quantity, setQuantity] = useState(1);

  function addFiveBroken() {
    setQuantity(quantity + 1);
    setQuantity(quantity + 1);
    setQuantity(quantity + 1);
    setQuantity(quantity + 1);
    setQuantity(quantity + 1);
  }

  return (
    <div>
      <p>Quantity: {quantity}</p>
      <button onClick={addFiveBroken}>+5</button>
    </div>
  );
}

export function QuantityStepperFixed() {
  const [quantity, setQuantity] = useState(1);

  function addFiveFixed() {
    setQuantity((current) => current + 1);
    setQuantity((current) => current + 1);
    setQuantity((current) => current + 1);
    setQuantity((current) => current + 1);
    setQuantity((current) => current + 1);
  }

  return (
    <div>
      <p>Quantity: {quantity}</p>
      <button onClick={addFiveFixed}>+5</button>
    </div>
  );
}

solutions/ex04_quantity_stepper.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { QuantityStepperBroken, QuantityStepperFixed } from "./ex04_quantity_stepper.jsx";

describe("QuantityStepperBroken: five calls from the same stale value", () => {
  it("only moves the quantity by 1, not 5, per click", async () => {
    const user = userEvent.setup();
    render(<QuantityStepperBroken />);

    expect(screen.getByText("Quantity: 1")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "+5" }));
    expect(screen.getByText("Quantity: 2")).toBeInTheDocument();
  });
});

describe("QuantityStepperFixed: each updater function sees the latest queued state", () => {
  it("really moves the quantity by 5 per click", async () => {
    const user = userEvent.setup();
    render(<QuantityStepperFixed />);

    expect(screen.getByText("Quantity: 1")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "+5" }));
    expect(screen.getByText("Quantity: 6")).toBeInTheDocument();
  });
});

solutions/ex05_city_filter_panel.jsx

// Exercise 5 solution: the lesson's RestaurantSearchPanelBroken/Fixed
// (section 6), renamed for a train search. Same bug, same fix, different
// domain - the broken siblings each keep their own disconnected `city`
// state; the fixed siblings share one `city`, lifted to their parent.

import { useState } from "react";

function CityFilterBoxBroken() {
  const [city, setCity] = useState("");
  return <input aria-label="Filter by city" value={city} onChange={(event) => setCity(event.target.value)} />;
}

function TrainResultsSummaryBroken() {
  const [city] = useState(""); // nothing outside this component ever sets it
  return <p>{city ? `Showing trains to "${city}"` : "Showing all trains"}</p>;
}

export function CityFilterPanelBroken() {
  return (
    <div>
      <CityFilterBoxBroken />
      <TrainResultsSummaryBroken />
    </div>
  );
}

function CityFilterBoxFixed({ city, onCityChange }) {
  return (
    <input aria-label="Filter by city" value={city} onChange={(event) => onCityChange(event.target.value)} />
  );
}

function TrainResultsSummaryFixed({ city }) {
  return <p>{city ? `Showing trains to "${city}"` : "Showing all trains"}</p>;
}

export function CityFilterPanelFixed() {
  const [city, setCity] = useState("");
  return (
    <div>
      <CityFilterBoxFixed city={city} onCityChange={setCity} />
      <TrainResultsSummaryFixed city={city} />
    </div>
  );
}

solutions/ex05_city_filter_panel.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { CityFilterPanelBroken, CityFilterPanelFixed } from "./ex05_city_filter_panel.jsx";

describe("CityFilterPanelBroken: duplicated state in two siblings", () => {
  it("never updates the results summary, because the two city states are not the same state", async () => {
    const user = userEvent.setup();
    render(<CityFilterPanelBroken />);

    expect(screen.getByText("Showing all trains")).toBeInTheDocument();

    await user.type(screen.getByLabelText("Filter by city"), "Pune");

    expect(screen.getByLabelText("Filter by city")).toHaveValue("Pune");
    expect(screen.getByText("Showing all trains")).toBeInTheDocument();
  });
});

describe("CityFilterPanelFixed: one city, lifted to the shared parent", () => {
  it("updates the sibling summary as soon as the city changes", async () => {
    const user = userEvent.setup();
    render(<CityFilterPanelFixed />);

    expect(screen.getByText("Showing all trains")).toBeInTheDocument();

    await user.type(screen.getByLabelText("Filter by city"), "Pune");

    expect(screen.getByLabelText("Filter by city")).toHaveValue("Pune");
    expect(screen.getByText('Showing trains to "Pune"')).toBeInTheDocument();
  });
});

solutions/ex06_coupon_field.jsx

// Exercise 6 solution: the lesson's PromoCodeControlled/PromoCodeUncontrolled
// pair (section 7), renamed for a checkout coupon field. Same contrast -
// who holds the current value while you type - just a different label.

import { useState } from "react";

export function CouponFieldControlled() {
  const [code, setCode] = useState("");

  return (
    <div>
      <input
        aria-label="Coupon code (controlled)"
        value={code}
        onChange={(event) => setCode(event.target.value.toUpperCase())}
      />
      <p>React's own state for this field: {code || "(empty)"}</p>
    </div>
  );
}

export function CouponFieldUncontrolled() {
  return (
    <div>
      <input aria-label="Coupon code (uncontrolled)" defaultValue="" />
      <p>React does not track this field's current value at all.</p>
    </div>
  );
}

solutions/ex06_coupon_field.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { CouponFieldControlled, CouponFieldUncontrolled } from "./ex06_coupon_field.jsx";

describe("CouponFieldControlled: React state mirrors the input on every keystroke", () => {
  it("shows the typed value both in the input and in React's own state readout", async () => {
    const user = userEvent.setup();
    render(<CouponFieldControlled />);

    expect(screen.getByText("React's own state for this field: (empty)")).toBeInTheDocument();

    await user.type(screen.getByLabelText("Coupon code (controlled)"), "save20");

    expect(screen.getByLabelText("Coupon code (controlled)")).toHaveValue("SAVE20");
    expect(screen.getByText("React's own state for this field: SAVE20")).toBeInTheDocument();
  });
});

describe("CouponFieldUncontrolled: the DOM node holds the value, React does not", () => {
  it("lets the real input value change while React's own output stays static", async () => {
    const user = userEvent.setup();
    render(<CouponFieldUncontrolled />);

    await user.type(screen.getByLabelText("Coupon code (uncontrolled)"), "save20");

    expect(screen.getByLabelText("Coupon code (uncontrolled)")).toHaveValue("save20");
    expect(screen.getByText("React does not track this field's current value at all.")).toBeInTheDocument();
  });
});

Common mistakes

Mistake Why it is wrong Fix
Expecting a plain variable or a mutated object to show up on screen React only re-renders when a state setter is called - it does not watch variables or poll for changes (section 2) Always read and change a displayed value through useState's own pair, never a plain variable
onClick={handleClick()} instead of onClick={handleClick} Calls the handler immediately during render instead of handing React a reference to call later - if the handler calls a setter, this produces React's real "Too many re-renders" crash (section 3) Pass the function itself, with no parentheses; wrap it in an inline arrow (onClick={() => handleClick(arg)}) only when it needs an argument the event itself does not supply
items.push(x), items[0] = x, or .sort()/.splice() on a piece of state Mutates the same array/object React is already holding, in place - the setter is never called, so React has no new reference to compare against and never re-renders, with no error at all (section 4) Build a new array/object first ([...items, x], .map(), .filter(), object spread) and pass that new value to the setter
setCount(count + 1) called more than once in the same handler, expecting it to add up Every call in one handler reads the same count - the value captured when this render started - so all of them compute from the same stale number (section 5) Pass a function instead: setCount(current => current + 1), once per call that needs to build on the one before it
Giving two sibling components their own, separate useState for "the same" value The two states are never actually connected - updating one never touches the other, no matter how related the variable names look (section 6) Lift the state to their closest common parent, and pass the value down to both (and the setter down to whichever one changes it)
Mixing value and defaultValue on the same <input>, or adding onChange to an otherwise-uncontrolled field "just in case" React logs a real warning about switching an input from uncontrolled to controlled (or back) between renders, and the field's behavior becomes unpredictable Pick one pattern per field and stay with it: value + onChange for controlled, defaultValue alone (no value, no onChange) for uncontrolled (section 7)

Quick recap

  • Props are a value only a parent can change by re-rendering; state is a value a component owns and changes itself, through the setter useState hands back - and state lives per component instance, not shared globally.
  • React re-renders only when a state setter is actually called with something new - it never watches plain variables and never polls.
  • onClick/onChange want a function reference, not the result of calling one - calling a setter during render instead of inside a later event schedules another render immediately, and repeating that is exactly React's "Too many re-renders" error.
  • Mutating state directly (.push(), index assignment, .sort()) changes the underlying value but never calls the setter, so React never finds out and never re-renders - build a new array/object and pass that to the setter instead.
  • Pass a function to a setter (setCount(c => c + 1)), not a plain value, whenever more than one update to the same state might happen before the next render - a value expression keeps reading the same stale number every time.
  • Lifting state up means moving a value to the closest common parent of every sibling that needs it, instead of letting each sibling keep its own disconnected copy.
  • A controlled input (value + onChange) keeps React state as the single source of truth for what it shows; an uncontrolled input (defaultValue only) lets the DOM hold the value instead - reading an uncontrolled field's value from code is Part 5's job, not this part's.

Checklist

  • I can explain, without looking it up, why a prop and a piece of state are different even when they hold the same kind of value.
  • I wrote a component with its own useState, and rendered two instances of it to confirm their state is independent.
  • I wired up both an onClick and an onChange handler correctly, and I know exactly what breaks (and why) if a handler is called instead of passed.
  • I reproduced the direct-mutation bug myself - clicked a button that calls .push() on state with no setter call - and watched the screen fail to update, then fixed it by building a new array first.
  • I reproduced the stale-value bug from calling a setter more than once in the same handler with a plain value, then fixed it with an updater function.
  • I lifted a piece of state out of a component into its parent so two siblings could share it, and confirmed both siblings actually stay in sync afterward.
  • I can say, in one sentence, who holds the current value for a controlled input versus an uncontrolled one.

Search the guide