React

Level recap · React · Level 2

State and events

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Make pages that answer clicks and typing, and load data.

14 classesLevel exam

Take the level exam
  1. 1State: a value that changes

    useState and a click.

    The idea

    Ticket CL-201: the Add to cart button should count how many the customer added.

    Props come from outside. A value that the component itself changes, like a count, is state. const [count, setCount] = useState(0); gives you the value now and a function to change it. When you call setCount(count + 1), React draws the component again with the new value.

    The code

    import { useState } from "react";
    function AddToCart() {
      const [count, setCount] = useState(0);
      return (
        <div>
          <button onClick={() => setCount(count + 1)}>Add to cart</button>
          <p>In your cart: {count}</p>
        </div>
      );
    }
    export default function App() {
      return <AddToCart />;
    }

    What it shows

    PASS Each button keeps its own count, from 0
  2. 2Plus and minus, with a floor

    State that starts from a prop and has limits.

    The idea

    Ticket CL-202: the quantity picker on the product page. It starts at the quantity already in the cart, goes up and down by one, and never goes below 1.

    State can start from a prop: useState(start) uses start only on the first draw. Each button changes the value; a limit is a normal test before you set it, or Math.max(1, qty - 1).

    The code

    import { useState } from "react";
    function Quantity({ start = 1 }) {
      const [qty, setQty] = useState(start);
      return (
        <div className="qty">
          <button aria-label="Less" onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
          <output>{qty}</output>
          <button aria-label="More" onClick={() => setQty(qty + 1)}>+</button>
        </div>
      );
    }
    export default function App() {
      return <Quantity start={2} />;
    }

    What it shows

    PASS It starts at the quantity it gets
  3. 3Typing into a box

    A controlled input: value and onChange.

    The idea

    Ticket CL-203: the search box at the top of the shop should repeat what the customer types, so they know what the results are for.

    A box whose value lives in state is called controlled. Two parts: value={query} shows the state in the box, and onChange={(e) => setQuery(e.target.value)} saves every key press. With only value, the box would not let anyone type.

    The code

    import { useState } from "react";
    function SearchBox() {
      const [query, setQuery] = useState("");
      return (
        <div>
          <input placeholder="Search products" value={query} onChange={(e) => setQuery(e.target.value)} />
          <p>{query ? `Results for "${query}"` : "Type to search"}</p>
        </div>
      );
    }
    export default function App() {
      return <SearchBox />;
    }

    What it shows

    PASS The line repeats what is typed
  4. 4Show and hide

    A true/false state and a button that flips it.

    The idea

    Ticket CL-204: the product page is too long. Put the delivery details behind a button.

    A true/false state is enough for anything that opens and closes: const [open, setOpen] = useState(false);. The button flips it with setOpen(!open), and the JSX draws the details only when open is true. The button's words can follow the state too.

    The code

    import { useState } from "react";
    function Delivery() {
      const [open, setOpen] = useState(false);
      return (
        <div>
          <button onClick={() => setOpen(!open)}>{open ? "Hide delivery details" : "Show delivery details"}</button>
          {open && <p className="details">Free delivery over $50. Orders placed before 2 pm leave the same day.</p>}
        </div>
      );
    }
    export default function App() {
      return <Delivery />;
    }

    What it shows

    PASS The details are hidden at first
  5. 5Send a form

    onSubmit, preventDefault, and clearing the box.

    The idea

    Ticket CL-205: the newsletter sign-up in the footer. After sending, thank the customer by email address and empty the box.

    Put the box and the button in a <form> and handle onSubmit, so Enter and the button both send it. A browser reloads the page when a form is sent; e.preventDefault() stops that, so your state survives.

    The code

    import { useState } from "react";
    function Newsletter() {
      const [email, setEmail] = useState("");
      const [sent, setSent] = useState("");
      function send(e) {
        e.preventDefault();
        setSent(email);
        setEmail("");
      }
      return (
        <form onSubmit={send}>
          <label>Email <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /></label>
          <button>Subscribe</button>
          {sent && <p className="thanks">Thanks, {sent}. Check your inbox.</p>}
        </form>
      );
    }
    export default function App() {
    …

    What it shows

    PASS Sending the form does not reload the page
  6. 6Add to a list in state

    A new array, never a changed one.

    The idea

    Ticket CL-206: the packing team's checklist page. They type a task, press Add, and it goes to the bottom of the list.

    To add to an array in state, make a new array: setTasks([...tasks, text]). Changing the old one with tasks.push(text) does not work: React sees the same array as before and does not draw again.

    The code

    import { useState } from "react";
    function Checklist() {
      const [tasks, setTasks] = useState([]);
      const [text, setText] = useState("");
      function add() {
        if (!text.trim()) return;
        setTasks([...tasks, text.trim()]);
        setText("");
      }
      return (
        <div>
          <input aria-label="New task" value={text} onChange={(e) => setText(e.target.value)} />
          <button onClick={add}>Add</button>
          <ul>{tasks.map((x, i) => <li key={i}>{x}</li>)}</ul>
        </div>
      );
    }
    export default function App() {
    …

    What it shows

    PASS Each added task goes to the end of the list
  7. 7Remove and tick items

    filter() to remove, map() to change one.

    The idea

    Ticket CL-207: on the same checklist, each task gets a tick box for done and a Remove button.

    To remove one item, keep all the others: setTasks(tasks.filter((x) => x.id !== id)). To change one, copy it with the change and keep the rest as they are: setTasks(tasks.map((x) => (x.id === id ? { ...x, done: !x.done } : x))). Both give back new arrays, so React draws again.

    The code

    import { useState } from "react";
    function Checklist({ initial }) {
      const [tasks, setTasks] = useState(initial);
      function remove(id) {
        setTasks(tasks.filter((x) => x.id !== id));
      }
      function toggle(id) {
        setTasks(tasks.map((x) => (x.id === id ? { ...x, done: !x.done } : x)));
      }
      return (
        <ul>
          {tasks.map((x) => (
            <li key={x.id} className={x.done ? "done" : ""}>
              <label><input type="checkbox" checked={x.done} onChange={() => toggle(x.id)} /> {x.title}</label>
              <button onClick={() => remove(x.id)}>Remove</button>
            </li>
          ))}
        </ul>
    …

    What it shows

    PASS Remove takes away only its own task
  8. 8An object in state

    Copy the object and change one field.

    The idea

    Ticket CL-208: the delivery form keeps the street and the city together as one address, and shows a preview line.

    When state is an object, make a new object with the old fields and the one change: setAddress({ ...address, city: e.target.value }). Writing setAddress({ city: e.target.value }) would drop the street.

    The code

    import { useState } from "react";
    function AddressForm() {
      const [address, setAddress] = useState({ street: "", city: "" });
      return (
        <div>
          <label>Street <input value={address.street} onChange={(e) => setAddress({ ...address, street: e.target.value })} /></label>
          <label>City <input value={address.city} onChange={(e) => setAddress({ ...address, city: e.target.value })} /></label>
          <p>Ship to: {address.street}, {address.city}</p>
        </div>
      );
    }
    export default function App() {
      return <AddressForm />;
    }

    What it shows

    PASS Typing the city keeps the street
  9. 9Lifting state up

    Two components share state through their parent.

    The idea

    Ticket CL-209: the search box and the product list are separate components, but the list must follow what is typed in the box.

    When two components need the same value, keep it in their closest parent and pass it down. The parent owns query; SearchBox gets value and onChange as props and only shows them; the list gets the filtered products. This is called lifting state up.

    The code

    import { useState } from "react";
    const products = [
      { id: 1, name: "Desk lamp" },
      { id: 2, name: "Lamp shade" },
      { id: 3, name: "Notebook" },
    ];
    function SearchBox({ value, onChange }) {
      return <input aria-label="Search" value={value} onChange={(e) => onChange(e.target.value)} />;
    }
    export default function App() {
      const [query, setQuery] = useState("");
      const shown = products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase()));
      return (
        <div>
          <SearchBox value={query} onChange={setQuery} />
          <ul>{shown.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
        </div>
      );
    …

    What it shows

    PASS SearchBox shows its value and reports what is typed
  10. 10Work it out, don't store it

    Values made from props and state on every draw.

    The idea

    Ticket CL-210, a bug report: when a customer changes a quantity in the cart, the total stays at the old amount.

    The total is made from the items, so it should not be state of its own. Work it out while drawing: const total = items.reduce((sum, x) => sum + x.price * x.qty, 0);. A copy kept in state goes stale the moment the items change; a value worked out on each draw is always right.

    The code

    import { useState } from "react";
    function Cart({ items }) {
      const total = items.reduce((s, x) => s + x.price * x.qty, 0);
      return (
        <div>
          <ul>{items.map((x) => <li key={x.id}>{x.name} × {x.qty}</li>)}</ul>
          <p className="total">Total: ${total.toFixed(2)}</p>
        </div>
      );
    }
    export default function App() {
      const [qty, setQty] = useState(1);
      const items = [{ id: 1, name: "Desk lamp", price: 39.5, qty }, { id: 2, name: "Notebook", price: 4, qty: 3 }];
      return (
        <div>
          <button onClick={() => setQty(qty + 1)}>One more lamp</button>
          <Cart items={items} />
        </div>
    …

    What it shows

    PASS The total is right for any items
  11. 11useEffect: change the page outside React

    Run code after a draw, when a value changes.

    The idea

    Ticket CL-211 from marketing: when there is something in the cart, the browser tab should say so, like (2) Copperleaf, so people come back to the tab.

    The tab's title is outside the part React draws, so you change it in an effect: useEffect(() => { document.title = ... }, [count]);. React runs it after the draw, and again only when a value in the list at the end changes. Leave the list out and it runs after every draw; an empty list [] runs it once.

    The code

    import { useState, useEffect } from "react";
    export default function App() {
      const [count, setCount] = useState(0);
      useEffect(() => {
        document.title = count > 0 ? `(${count}) Copperleaf` : "Copperleaf";
      }, [count]);
      return (
        <div>
          <button onClick={() => setCount(count + 1)}>Add to cart</button>
          <p>In your cart: {count}</p>
        </div>
      );
    }

    What it shows

    PASS With an empty cart the tab says Copperleaf
  12. 12Clean up after an effect

    Stop timers when a component leaves the page.

    The idea

    Ticket CL-212, a bug report: the flash-sale countdown keeps running after the customer leaves the page, and the browser gets slower and slower.

    An effect can give back a function. React calls it when the component leaves the page, or before the effect runs again. That is where you undo what the effect started: const id = setInterval(tick, 1000); return () => clearInterval(id);.

    The code

    import { useState, useEffect } from "react";
    function Countdown({ seconds }) {
      const [left, setLeft] = useState(seconds);
      useEffect(() => {
        const id = setInterval(() => setLeft((s) => Math.max(0, s - 1)), 1000);
        return () => clearInterval(id);
      }, []);
      return <p className="sale">{left > 0 ? `Sale ends in ${left} s` : "Sale over"}</p>;
    }
    export default function App() {
      const [shown, setShown] = useState(true);
      return (
        <div>
          <button onClick={() => setShown(!shown)}>{shown ? "Leave the page" : "Come back"}</button>
          {shown && <Countdown seconds={20} />}
        </div>
      );
    }

    What it shows

    PASS It counts down one second at a time and stops at Sale over
  13. 13Load data: loading, error and empty

    Fetch in an effect and show every state.

    The idea

    Ticket CL-213: the product page now loads the catalog from the server. On a slow connection, a dead server or an empty catalog, the page must still say something useful.

    Load data in an effect with [], so it runs once. Keep three pieces of state: the data, whether it is still loading, and an error. Draw the right one: Loading products… while waiting, Could not load products. if the request failed, No products yet. for an empty list, and the list otherwise.

    The code

    import { useState, useEffect } from "react";
    function Products() {
      const [items, setItems] = useState([]);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(false);
      useEffect(() => {
        fetch("/api/products")
          .then((res) => {
            if (!res.ok) throw new Error("Bad answer");
            return res.json();
          })
          .then((data) => setItems(data))
          .catch(() => setError(true))
          .finally(() => setLoading(false));
      }, []);
      if (loading) return <p>Loading products…</p>;
      if (error) return <p>Could not load products.</p>;
      if (items.length === 0) return <p>No products yet.</p>;
    …

    What it shows

    PASS It shows Loading first, then the products
  14. 14Your own hook

    Put state and an effect in a function to reuse.

    The idea

    Ticket CL-214: three pages need to remember a choice after a reload: the list or grid view, the sort order, and the last search. Write it once.

    A custom hook is a function whose name starts with use and that calls other hooks. useSaved(key, start) can keep a value in state, read the saved one first, and save it whenever it changes, then give back [value, setValue] like useState does. Any component can use it.

    The code

    import { useState, useEffect } from "react";
    function useSaved(key, start) {
      const [value, setValue] = useState(() => {
        const saved = localStorage.getItem(key);
        return saved === null ? start : JSON.parse(saved);
      });
      useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
      }, [key, value]);
      return [value, setValue];
    }
    export default function App() {
      const [view, setView] = useSaved("view", "grid");
      return (
        <div>
          <p>View: {view}</p>
          <button onClick={() => setView(view === "grid" ? "list" : "grid")}>Switch view</button>
        </div>
    …

    What it shows

    PASS It starts from the saved value, or from start

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam