Level recap · React · Level 3
A real app
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: Share state across a page, move between pages, check forms, keep it fast, accessible and tested.
15 classesLevel exam
1Context: a value for the whole page
createContext, a Provider and useContext.
The idea
Ticket CL-301 from the design lead: the shop gets a dark theme. The Switch theme button sits at the top of the page, but the buttons that change color are deep inside the toolbar.
Passing
themedown through every component in between works, but every part in the middle has to carry a prop it never uses. Context skips the middle.const ThemeContext = createContext("light");makes it,<ThemeContext.Provider value={theme}>puts a value around a part of the page, and any component inside reads it withconst theme = useContext(ThemeContext);.The code
import { createContext, useContext, useState } from "react"; const ThemeContext = createContext("light"); function ThemedButton({ children }) { const theme = useContext(ThemeContext); return <button className={"btn " + theme}>{children}</button>; } function Toolbar() { return ( <div className="bar"> <ThemedButton>Save</ThemedButton> <ThemedButton>Share</ThemedButton> </div> ); } export default function App() { const [theme, setTheme] = useState("light"); return ( <div> …What it shows
PASS ThemedButton takes its theme from the Provider
2A cart the whole page can use
A provider component that holds state.
The idea
Ticket CL-302: the cart badge in the header and the Add to cart buttons on the product cards are far apart on the page, and both need the same cart.
Put the state in one component that only provides it:
CartProviderkeepsitemsin state and gives{ items, add }to everything inside it with<CartContext.Provider value={{ items, add }}>{children}</CartContext.Provider>.The code
import { createContext, useContext, useState } from "react"; const CartContext = createContext(null); function CartProvider({ children }) { const [items, setItems] = useState([]); const add = (product) => setItems([...items, product]); return <CartContext.Provider value={{ items, add }}>{children}</CartContext.Provider>; } function useCart() { return useContext(CartContext); } function CartBadge() { const { items } = useCart(); return <p className="badge">Cart ({items.length})</p>; } function ProductCard({ product }) { const { add } = useCart(); return ( <div className="card"> …What it shows
PASS Add to cart on any card counts in the badge
3Start fresh with a key
A new key gives a component new state.
The idea
Ticket CL-303, a bug report from customer support: when an agent switches from one customer to the next, the note box still shows the note for the last customer. Twice a note was saved on the wrong account.
React keeps a component's state while the same component stays in the same place, even when its props change. Here
NoteBoxstays put and only gets a newcustomer, so itsnotestate stays too.The code
import { useState } from "react"; function NoteBox({ customer }) { const [note, setNote] = useState(""); return ( <label> Note for {customer.name} <textarea value={note} onChange={(e) => setNote(e.target.value)} /> </label> ); } const CUSTOMERS = [{ id: 1, name: "Ava Morgan" }, { id: 2, name: "Leo Hart" }, { id: 3, name: "Mia Stone" }]; export default function App({ customers = CUSTOMERS }) { const [currentId, setCurrentId] = useState(customers[0].id); const current = customers.find((x) => x.id === currentId); return ( <div> {customers.map((x) => <button key={x.id} onClick={() => setCurrentId(x.id)}>{x.name}</button>)} <NoteBox key={current.id} customer={current} /> …What it shows
PASS Switching customer gives an empty note box
4All the cart rules in one place
A reducer: (state, action) gives the next state.
The idea
Ticket CL-304 from the lead developer: the cart code is spread over five click handlers, and two of them disagree about what happens when a quantity goes to 0. Put every rule in one function.
A reducer is a plain function: it gets the state now and an action that says what happened, and gives back the next state.
cartReducer(items, { type: "add", product }). React calls it for you throughuseReducer.The code
import { useReducer } from "react"; function cartReducer(state, action) { switch (action.type) { case "add": { const line = state.find((x) => x.id === action.product.id); if (line) return state.map((x) => (x.id === action.product.id ? { ...x, qty: x.qty + 1 } : x)); return [...state, { ...action.product, qty: 1 }]; } case "remove": return state.filter((x) => x.id !== action.id); case "setQty": if (action.qty < 1) return state.filter((x) => x.id !== action.id); return state.map((x) => (x.id === action.id ? { ...x, qty: action.qty } : x)); default: return state; } } export default function App() { …What it shows
PASS add puts a new product in, or adds one to its qty
5Connect the reducer to the page
useReducer and dispatch.
The idea
Ticket CL-305: the cart rules are done and tested. Now the shop page should use them.
const [items, dispatch] = useReducer(cartReducer, []);works likeuseState, but instead of a setter you getdispatch. A click sends an action:dispatch({ type: "add", product: p }). React runs the reducer and draws the page with what it gives back.The code
import { useReducer } from "react"; function cartReducer(state, action) { switch (action.type) { case "add": { const line = state.find((x) => x.id === action.product.id); if (line) return state.map((x) => (x.id === action.product.id ? { ...x, qty: x.qty + 1 } : x)); return [...state, { ...action.product, qty: 1 }]; } case "remove": return state.filter((x) => x.id !== action.id); default: return state; } } function Shop({ products }) { const [items, dispatch] = useReducer(cartReducer, []); const total = items.reduce((s, x) => s + x.price * x.qty, 0); return ( …What it shows
PASS The Add buttons fill the cart for any products
6Pages without a reload
State that says which page is open.
The idea
Ticket CL-306: the shop should move between Home, Products and Cart without loading the whole page again, and the menu must show where the customer is.
The open page is just state:
const [pageId, setPageId] = useState(pages[0].id);. The menu buttons set it, and the main part draws the page that matches. Router libraries add the web address on top of this, but the idea is the same.The code
import { useState } from "react"; const PAGES = [ { id: "home", label: "Home", title: "Welcome to Copperleaf" }, { id: "products", label: "Products", title: "All products" }, { id: "cart", label: "Cart", title: "Your cart" }, ]; export default function App({ pages = PAGES }) { const [pageId, setPageId] = useState(pages[0].id); const page = pages.find((p) => p.id === pageId); return ( <div> <nav> {pages.map((p) => ( <button key={p.id} aria-current={p.id === pageId ? "page" : undefined} onClick={() => setPageId(p.id)}>{p.label}</button> ))} </nav> <main> <h1>{page.title}</h1> …What it shows
PASS Each menu button opens its page
7A page for each product
Read the id from the address, and handle a wrong one.
The idea
Ticket CL-307: every product gets its own address, like
/products/12, so customers can share a link. Old links to products we no longer sell must not break the page.Part of the address is a value: in
/products/12the12says which product. A regular expression can read it:/^\/products\/(\d+)$/.exec(path)gives the digits inm[1], ornullwhen the path does not match. Turn them into a number withNumber(m[1]).The code
function matchProduct(path) { const m = /^\/products\/(\d+)$/.exec(path); return m ? Number(m[1]) : null; } function ProductPage({ id, products }) { const product = products.find((p) => p.id === id); if (!product) return <p>Product not found.</p>; return ( <div> <h1>{product.name}</h1> <p className="price">{"$" + product.price.toFixed(2)}</p> </div> ); } const PRODUCTS = [{ id: 7, name: "Desk lamp", price: 39.5 }, { id: 12, name: "Monitor arm", price: 89 }]; export default function App() { const path = "/products/12"; return <ProductPage id={matchProduct(path)} products={PRODUCTS} />; …What it shows
PASS matchProduct reads the id from the path
8Check the form before it is sent
Messages next to the boxes that are wrong.
The idea
Ticket CL-308 from the payments team: orders arrive with no name or with emails like
anna.example.com, and the confirmation email never reaches the customer.Check the boxes in
onSubmitbefore anything is sent. Start withe.preventDefault(), so the browser does not reload the page. Collect the problems in an object, like{ email: "Enter an email like name@example.com." }, keep it in state, and show each message under its box.The code
import { useState } from "react"; function Checkout() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [errors, setErrors] = useState({}); const [placed, setPlaced] = useState(""); function send(e) { e.preventDefault(); const next = {}; if (!name.trim()) next.name = "Enter your name."; if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) next.email = "Enter an email like name@example.com."; setErrors(next); if (Object.keys(next).length === 0) setPlaced(name.trim()); } if (placed) return <p>Order placed for {placed}.</p>; return ( <form onSubmit={send}> <label>Name <input value={name} onChange={(e) => setName(e.target.value)} /></label> …What it shows
PASS Empty or wrong boxes show their message
9Take the customer to the first mistake
useRef, focus and the aria attributes for errors.
The idea
Ticket CL-309 from the accessibility review: when the checkout form has a mistake, people using a keyboard or a screen reader cannot tell which box is wrong.
useRefgives you a box that holds the real input:const nameRef = useRef(null);and<input ref={nameRef} />. After a failed check,nameRef.current.focus()puts the cursor there.The code
import { useState, useRef } from "react"; function Checkout() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [errors, setErrors] = useState({}); const [placed, setPlaced] = useState(""); const nameRef = useRef(null); const emailRef = useRef(null); function send(e) { e.preventDefault(); const next = {}; if (!name.trim()) next.name = "Enter your name."; if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) next.email = "Enter an email like name@example.com."; setErrors(next); if (next.name) nameRef.current.focus(); else if (next.email) emailRef.current.focus(); if (Object.keys(next).length === 0) setPlaced(name.trim()); } …What it shows
PASS The first wrong box gets the focus
10One broken part, not a blank page
An error boundary shows a message instead.
The idea
Ticket CL-310, an incident report: last night the reviews service sent bad data, the reviews part stopped with an error, and React removed the whole product page. Customers saw a white screen and could not buy.
When a component stops with an error while drawing, React takes down everything above it, up to the nearest error boundary. A boundary is a class component with
static getDerivedStateFromError(): it notes the error in state, andrender()then shows a message instead of its children.The code
import { Component } from "react"; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { failed: false }; } static getDerivedStateFromError() { return { failed: true }; } render() { if (this.state.failed) { return ( <div role="alert"> <p>This part could not load.</p> <button onClick={() => this.setState({ failed: false })}>Try again</button> </div> ); } …What it shows
PASS A broken part shows the message, and the rest of the page stays
11Buttons a screen reader can name
aria-label for icon buttons and boxes without a label.
The idea
Ticket CL-311 from the accessibility review: in the cart, a screen reader reads every remove button only as "button" and every quantity box as "spin button". A blind customer cannot tell which product a button removes.
A button with only an icon has no name. Give it one with
aria-label:aria-label={"Remove " + x.name}. Put the product's name in it, because there is one button per line and "Remove" alone does not say which.The code
import { useState } from "react"; const TrashIcon = () => ( <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"> <path d="M3 4h10M6 4V2h4v2M5 4l1 10h4l1-10" fill="none" stroke="currentColor" strokeWidth="1.5" /> </svg> ); function CartLines({ items, onRemove, onQty }) { return ( <ul> {items.map((x) => ( <li key={x.id}> {x.name} <input type="number" min="1" value={x.qty} aria-label={"Quantity for " + x.name} onChange={(e) => onQty(x.id, Number(e.target.value))} /> <button aria-label={"Remove " + x.name} onClick={() => onRemove(x.id)}><TrashIcon /></button> </li> ))} </ul> ); …What it shows
PASS Each remove button says Remove and the product's name
12Say it out loud: status messages
A role="status" box that is always on the page.
The idea
Ticket CL-312 from the accessibility review: after Add, sighted customers see "Desk lamp added to the cart.", but a screen reader says nothing.
A box with
role="status"tells a screen reader to read out any new text that appears in it. The catch: it reads changes in a box that was already on the page. A box that appears together with its text is often missed.The code
import { useState } from "react"; function AddButtons({ products }) { const [msg, setMsg] = useState(""); return ( <div> {products.map((p) => ( <button key={p.id} onClick={() => setMsg(p.name + " added to the cart.")}>Add {p.name}</button> ))} <p role="status">{msg}</p> </div> ); } const PRODUCTS = [{ id: 1, name: "Desk lamp" }, { id: 2, name: "Notebook" }]; export default function App() { return <AddButtons products={PRODUCTS} />; }What it shows
PASS The status box is on the page from the start, empty
13Skip drawing what did not change
memo() redraws a component only when its props change.
The idea
Ticket CL-313, a speed report: on the stock page with 2,000 products, typing in the Note for the team box is slow, because every key press draws every product row again.
When a component's state changes, React draws it and all the components inside it again. Usually that is fast. When a part is costly and its props did not change, wrap it in
memo:const ProductRow = memo(function ProductRow({ product }) { ... });. React then skips it unless one of its props is a different value.The code
import { useState, memo } from "react"; const ProductRow = memo(function ProductRow({ product }) { return <li>{product.name} <span className="price">{"$" + product.price.toFixed(2)}</span></li>; }); const PRODUCTS = [{ id: 1, name: "Desk lamp", price: 39.5 }, { id: 2, name: "Notebook", price: 4 }, { id: 3, name: "Monitor arm", price: 89 }]; export default function App({ products = PRODUCTS }) { const [note, setNote] = useState(""); return ( <div> <label>Note for the team <input value={note} onChange={(e) => setNote(e.target.value)} /></label> <ul>{products.map((p) => <ProductRow key={p.id} product={p} />)}</ul> </div> ); }What it shows
PASS Typing a note does not draw the rows again
14Keep slow work and handlers between draws
useMemo for a result, useCallback for a function.
The idea
Ticket CL-314, the same speed report: on the stock page, the rows are in
memonow, but typing a note still sorts 2,000 products and still draws every row.Two causes. The list is sorted again on every draw: keep the result with
useMemo(() => sortByPrice(products), [products]), which runs the sort again only whenproductschanges. Andaddis a new function on every draw, somemosees a new prop on every row: keep it withuseCallback.The code
import { useState, memo, useMemo, useCallback } from "react"; function sortByPrice(list) { return [...list].sort((a, b) => a.price - b.price); } const Row = memo(function Row({ product, onAdd }) { return <li>{product.name} {"$" + product.price.toFixed(2)} <button onClick={() => onAdd(product.id)}>Add</button></li>; }); function Shop({ products }) { const [note, setNote] = useState(""); const [cart, setCart] = useState([]); const sorted = useMemo(() => sortByPrice(products), [products]); const add = useCallback((id) => setCart((c) => [...c, id]), []); return ( <div> <label>Note for the team <input value={note} onChange={(e) => setNote(e.target.value)} /></label> <p>In the cart: {cart.length}</p> <ul>{sorted.map((p) => <Row key={p.id} product={p} onAdd={add} />)}</ul> </div> …What it shows
PASS The sort runs again only when the products change
15Test a component
Tests that click like a customer and catch a broken change.
The idea
Ticket CL-315 from the lead developer: last month someone changed the quantity counter and nobody noticed that Plus went past the stock limit. From now on, every component comes with tests.
A test draws the component, does what a customer does, and checks what is on the page. This page has the same tools teams use:
test("name", async () => { ... }),render(<Counter start={3} />)which gives back finders likegetByText,user.click(...), andexpect(value).toBeTruthy().The code
import { useState } from "react"; function Counter({ start = 0, max = 10 }) { const [n, setN] = useState(start); return ( <div> <p>Count: {n}</p> <button onClick={() => setN(n - 1)}>Minus</button> <button onClick={() => setN(Math.min(max, n + 1))}>Plus</button> </div> ); } test("starts at the start value", async () => { const s = render(<Counter start={3} />); expect(s.getByText("Count: 3")).toBeTruthy(); }); test("Plus adds one", async () => { const s = render(<Counter start={1} />); await user.click(s.getByText("Plus")); …What it shows
PASS Your tests pass on the working Counter
Ready for the exam? The level exam is one real task that uses what this recap covers.
Take the level exam