Skip to content

Come Back Later

The Course
•
20 min study

Come back to this a few days after finishing the course. Try everything without looking back at earlier lessons first.

Bug hunt

This Study Hub has four bugs, from Days 2, 3, 4 and 5. Try these, in order, and note what goes wrong each time:

  1. Tick External stores, then open Stats.
  2. Back in Topics, type win in Filter, open Focus timer, and come back.
  3. Press Ctrl+K, then Escape, then Ctrl+K again.
  4. Select Windowing, wait for the error, and press Try again.
Four bugs React · 20 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { lazy, Suspense, useState } from "react"; import CommandPalette from "./components/CommandPalette.jsx"; import { Tab, TabList, TabPanel, Tabs } from "./components/Tabs.jsx"; import FocusTimer from "./timer/FocusTimer.jsx"; import TopicsPanel from "./topics/TopicsPanel.jsx"; // A real build would download Stats as a separate chunk; the wait shows that. const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const StatsPanel = lazy(() => wait(600).then(() => import("./stats/StatsPanel.jsx"))); export default function App() { const [tab, setTab] = useState("topics"); const [status, setStatus] = useState(""); return ( <main> <header> <h1>Study Hub</h1> <CommandPalette onTab={setTab} onRun={(command) => setStatus(`Ran: ${command}`)} /> </header> <p className="muted" role="status">{status}</p> <Tabs value={tab} onChange={setTab}> <TabList label="Study Hub sections"> <Tab value="topics">Topics</Tab> <Tab value="timer">Focus timer</Tab> <Tab value="stats">Stats</Tab> </TabList> <TabPanel value="topics"><TopicsPanel /></TabPanel> <TabPanel value="timer"><FocusTimer /></TabPanel> <TabPanel value="stats"> <Suspense fallback={<p className="muted">Loading stats…</p>}> <StatsPanel /> </Suspense> </TabPanel> </Tabs> </main> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; } header { display: flex; justify-content: space-between; align-items: center; gap: 1rem; } kbd { font: 12px ui-monospace, monospace; border: 1px solid #c3ccd6; border-radius: 4px; padding: 0 0.3rem; } .topics { display: grid; grid-template-columns: 1fr 1.3fr; gap: 1rem; } .topics ul { list-style: none; padding: 0; margin: 0.5rem 0 0; } .topics li { display: flex; gap: 0.4rem; align-items: center; padding: 0.15rem 0; } .topics li button { border: 0; background: none; padding: 0.1rem 0.2rem; text-align: left; color: #06617f; } .topics li button[aria-current="true"] { font-weight: 700; } .pending { opacity: 0.6; } .bar { height: 0.5rem; border-radius: 999px; background: #e3e8ee; overflow: hidden; } .bar span { display: block; height: 100%; background: #087ea4; } .clock { font-size: 2rem; font-variant-numeric: tabular-nums; margin: 0.25rem 0 0.5rem; } import { useId, useState } from "react"; // A text box with a list of suggestions. Focus stays in the input; the // highlighted option is announced through aria-activedescendant. export default function Combobox({ label, options, onSelect }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); const id = useId(); const listId = `${id}-list`; const matches = options.filter((o) => o.toLowerCase().includes(query.trim().toLowerCase())); const optionId = (index) => `${id}-option-${index}`; function choose(option) { setQuery(option); setOpen(false); setActiveIndex(-1); onSelect(option); } function handleKeyDown(event) { if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActiveIndex((i) => Math.min(i + 1, matches.length - 1)); } else if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (event.key === "Enter" && open && activeIndex >= 0) { event.preventDefault(); choose(matches[activeIndex]); } else if (event.key === "Escape") { setOpen(false); setActiveIndex(-1); } } return ( <div> <label htmlFor={`${id}-input`}>{label}</label>{" "} <input id={`${id}-input`} role="combobox" aria-expanded={open} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined} value={query} onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }} onKeyDown={handleKeyDown} /> {open && matches.length > 0 && ( <ul role="listbox" id={listId} aria-label={label}> {matches.map((option, index) => ( <li key={option} id={optionId(index)} role="option" aria-selected={index === activeIndex} data-active={index === activeIndex} onMouseDown={(e) => e.preventDefault()} onClick={() => choose(option)} > {option} </li> ))} </ul> )} </div> ); } import { useEffect, useState } from "react"; import { resetProgress } from "../store/progress.js"; import { send } from "../store/timer.js"; import Combobox from "./Combobox.jsx"; import Dialog from "./Dialog.jsx"; // Every command is a name and what it does. The palette knows nothing else // about the app. function commandsFor(onTab) { return { "Go to Topics": () => onTab("topics"), "Go to Focus timer": () => onTab("timer"), "Go to Stats": () => onTab("stats"), "Start focus session": () => { send("START"); onTab("timer"); }, "Reset progress": () => resetProgress(), }; } export default function CommandPalette({ onTab, onRun }) { const [open, setOpen] = useState(false); const commands = commandsFor(onTab); // Ctrl+K or ⌘K opens the palette from anywhere on the page. useEffect(() => { function handleKeyDown(event) { if (event.key.toLowerCase() === "k" && (event.ctrlKey || event.metaKey)) { event.preventDefault(); setOpen(true); } } window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, []); function run(name) { setOpen(false); commands[name](); onRun(name); } return ( <> <button onClick={() => setOpen(true)}>Commands <kbd>Ctrl K</kbd></button> <Dialog open={open} title="Command palette"> {open && <Combobox label="Command" options={Object.keys(commands)} onSelect={run} />} </Dialog> </> ); } import { useEffect, useRef } from "react"; // The browser's own modal dialog: it moves focus inside, blocks the page // behind it, closes on Escape, and returns focus to whatever opened it. export default function Dialog({ open, onClose, title, children }) { const ref = useRef(null); // Keep the real <dialog> in step with the open prop. useEffect(() => { const dialog = ref.current; if (open && !dialog.open) dialog.showModal(); if (!open && dialog.open) dialog.close(); }, [open]); return ( <dialog ref={ref} onClose={onClose} aria-labelledby="dialog-title"> <h2 id="dialog-title">{title}</h2> {children} </dialog> ); } import { Component } from "react"; // Catches rendering errors below it and shows fallback(error, reset). // When resetKey changes, it clears the error without remounting its children, // so a Suspense boundary inside it keeps its content during a transition. export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidUpdate(previous) { if (this.state.error && previous.resetKey !== this.props.resetKey) this.reset(); } reset = () => this.setState({ error: null }); render() { if (this.state.error) return this.props.fallback(this.state.error, this.reset); return this.props.children; } } import { createContext, useContext, useId, useRef } from "react"; // Compound, controlled tabs (Day 1) with a roving tabindex (Day 5). Hidden // panels are left out. const TabsContext = createContext(null); function useTabs(part) { const tabs = useContext(TabsContext); if (tabs === null) throw new Error(`<${part}> must be used inside <Tabs>.`); return tabs; } export function Tabs({ value, onChange, children }) { const baseId = useId(); return <TabsContext value={{ selected: value, select: onChange, baseId }}>{children}</TabsContext>; } export function TabList({ label, children }) { useTabs("TabList"); const listRef = useRef(null); function handleKeyDown(event) { const tabs = [...listRef.current.querySelectorAll('[role="tab"]')]; const index = tabs.indexOf(document.activeElement); const next = { ArrowRight: (index + 1) % tabs.length, ArrowLeft: (index - 1 + tabs.length) % tabs.length, Home: 0, End: tabs.length - 1, }[event.key]; if (next === undefined) return; event.preventDefault(); tabs[next].focus(); tabs[next].click(); } return ( <div role="tablist" aria-label={label} ref={listRef} onKeyDown={handleKeyDown}> {children} </div> ); } export function Tab({ value, children }) { const { selected, select, baseId } = useTabs("Tab"); const isSelected = selected === value; return ( <button role="tab" id={`${baseId}-tab-${value}`} aria-selected={isSelected} aria-controls={`${baseId}-panel-${value}`} tabIndex={isSelected ? 0 : -1} onClick={() => select(value)} > {children} </button> ); } export function TabPanel({ value, children }) { const { selected, baseId } = useTabs("TabPanel"); if (selected !== value) return null; return ( <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`} tabIndex={0}> {children} </div> ); } import { topics } from "./topics.js"; const summaries = { 1: "Parts that share state through context, so users arrange them freely.", 2: "A value prop and an onChange, so the parent owns the state.", 3: "State outside React, read with useSyncExternalStore.", 4: "Every state lists the events it accepts, and where each leads.", 5: "Read a promise during render; a boundary shows the fallback.", 6: "Load a component's code only when it's first needed.", 7: "Measure with the Profiler before changing anything.", 8: "Render only the rows that are on screen.", 9: "showModal() handles focus, the backdrop and Escape.", 10: "Focus stays in the input; aria-activedescendant names the active option.", 11: "renderHook, rerender and fake timers.", 12: "vi.mock at the edges: the network, the clock, storage.", }; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); let windowingFailed = false; // A pretend server. Windowing fails the first time, so you can try the error // boundary's Try again. export async function fetchTopic(id) { console.log(`request: topic ${id}`); await wait(500); if (id === 8 && !windowingFailed) { windowingFailed = true; throw new Error("The server timed out."); } return { ...topics.find((t) => t.id === id), summary: summaries[id] }; } import { fetchTopic } from "./api.js"; // One promise per topic, reused on every render, as use() needs. const cache = new Map(); export function getTopic(id) { if (!cache.has(id)) cache.set(id, fetchTopic(id)); return cache.get(id); } export function invalidate(id) { cache.delete(id); } // Each day's topics. Details come from the pretend server in api.js. export const topics = [ { id: 1, day: 1, title: "Compound components" }, { id: 2, day: 1, title: "Controlled props" }, { id: 3, day: 2, title: "External stores" }, { id: 4, day: 2, title: "State machines" }, { id: 5, day: 3, title: "Suspense and use" }, { id: 6, day: 3, title: "Lazy loading" }, { id: 7, day: 4, title: "Profiling" }, { id: 8, day: 4, title: "Windowing" }, { id: 9, day: 5, title: "Dialogs" }, { id: 10, day: 5, title: "Comboboxes" }, { id: 11, day: 6, title: "Testing hooks" }, { id: 12, day: 6, title: "Mocking the server" }, ]; import { topics } from "../data/topics.js"; import { doneCount, progress } from "../store/progress.js"; import { timer } from "../store/timer.js"; import { useStore } from "../store/useStore.js"; export default function StatsPanel() { const done = useStore(progress, doneCount); const sessions = useStore(timer, (s) => s.sessions); const percent = Math.round((done / topics.length) * 100); return ( <section> <h2>{done} of {topics.length} topics done</h2> <div className="bar" role="progressbar" aria-label="Topics done" aria-valuenow={percent} aria-valuemin={0} aria-valuemax={100}> <span style={{ width: `${percent}%` }} /> </div> <p>Focus sessions finished: {sessions}</p> </section> ); } // The timer as a state machine: every state lists the events it accepts, and // where each one leads. Anything not listed is ignored. export const machine = { idle: { START: "focusing" }, focusing: { PAUSE: "paused", FINISH: "onBreak", RESET: "idle" }, paused: { RESUME: "focusing", RESET: "idle" }, onBreak: { FINISH: "idle", RESET: "idle" }, }; export function transition(status, event) { return machine[status][event] ?? status; } export function can(status, event) { return event in machine[status]; } import { createStore } from "./store.js"; // Which topics are done. Outside React, so the palette, the topic list and // the stats all share it without passing props. export const progress = createStore({ done: [] }); export function toggleDone(id) { progress.setState((state) => { if (state.done.includes(id)) state.done.splice(state.done.indexOf(id), 1); else state.done.push(id); return state; }); } export function resetProgress() { progress.setState({ done: [] }); } // Selectors return a number or a boolean, so components re-render only when // the answer changes. export const doneCount = (state) => state.done.length; export const isDone = (id) => (state) => state.done.includes(id); // A tiny store: state that lives outside React. Any code can read it, change // it, or subscribe to changes, including code that isn't a component. export function createStore(initialState) { let state = initialState; const listeners = new Set(); return { getState: () => state, setState(update) { const next = typeof update === "function" ? update(state) : update; if (Object.is(next, state)) return; state = next; listeners.forEach((listener) => listener()); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, }; } import { transition } from "./machine.js"; import { createStore } from "./store.js"; export const FOCUS_SECONDS = 25 * 60; export const timer = createStore({ status: "idle", remaining: FOCUS_SECONDS, sessions: 0 }); let ticker = null; export function send(event) { timer.setState((state) => { const status = transition(state.status, event); if (status === state.status) return state; const finishedFocus = state.status === "focusing" && status === "onBreak"; return { status, remaining: status === "idle" ? FOCUS_SECONDS : state.remaining, sessions: state.sessions + (finishedFocus ? 1 : 0), }; }); // The ticker runs only while focusing, outside React, so the timer keeps // going whichever tab is showing. const focusing = timer.getState().status === "focusing"; if (focusing && ticker === null) ticker = setInterval(tick, 1000); if (!focusing && ticker !== null) { clearInterval(ticker); ticker = null; } } function tick() { if (timer.getState().remaining <= 1) send("FINISH"); else timer.setState((state) => ({ ...state, remaining: state.remaining - 1 })); } import { useSyncExternalStore } from "react"; // Re-renders only when the selected part of the state changes. export function useStore(store, selector = (state) => state) { return useSyncExternalStore(store.subscribe, () => selector(store.getState())); } import { can } from "../store/machine.js"; import { send, timer } from "../store/timer.js"; import { useStore } from "../store/useStore.js"; const labels = { idle: "Ready", focusing: "Focusing", paused: "Paused", onBreak: "On a break" }; const clock = (s) => `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`; export default function FocusTimer() { const status = useStore(timer, (s) => s.status); const remaining = useStore(timer, (s) => s.remaining); return ( <section> <h2>{labels[status]}</h2> <p className="clock">{clock(remaining)}</p> <div className="toolbar"> {["START", "PAUSE", "RESUME", "FINISH", "RESET"].map((event) => ( <button key={event} onClick={() => send(event)} disabled={!can(status, event)}> {event[0] + event.slice(1).toLowerCase()} </button> ))} </div> </section> ); } import { use } from "react"; import { getTopic } from "../data/cache.js"; export default function TopicDetails({ id }) { const topic = use(getTopic(id)); return ( <article className="card"> <h2>{topic.title}</h2> <p className="muted">Day {topic.day}</p> <p>{topic.summary}</p> </article> ); } import { Suspense, useState, useTransition } from "react"; import ErrorBoundary from "../components/ErrorBoundary.jsx"; import { topics } from "../data/topics.js"; import { isDone, progress, toggleDone } from "../store/progress.js"; import { useStore } from "../store/useStore.js"; import TopicDetails from "./TopicDetails.jsx"; function TopicRow({ topic, selected, onSelect }) { const done = useStore(progress, isDone(topic.id)); return ( <li> <input type="checkbox" checked={done} onChange={() => toggleDone(topic.id)} aria-label={`${topic.title} done`} /> <button aria-current={selected} onClick={() => onSelect(topic.id)}>{topic.title}</button> </li> ); } export default function TopicsPanel() { const [filter, setFilter] = useState(""); const [selectedId, setSelectedId] = useState(1); const [attempt, setAttempt] = useState(0); const [isPending, startTransition] = useTransition(); const shown = topics.filter((t) => t.title.toLowerCase().includes(filter.trim().toLowerCase())); function select(id) { // Keep the current details on screen while the next ones load. startTransition(() => setSelectedId(id)); } return ( <div className="topics"> <section> <label> Filter <input value={filter} onChange={(e) => setFilter(e.target.value)} /> </label> <ul> {shown.map((t) => ( <TopicRow key={t.id} topic={t} selected={t.id === selectedId} onSelect={select} /> ))} </ul> </section> <section className={isPending ? "pending" : undefined}> <ErrorBoundary resetKey={`${selectedId}:${attempt}`} fallback={(error) => ( <div role="alert"> <p className="error">{error.message}</p> <button onClick={() => setAttempt((a) => a + 1)}>Try again</button> </div> )} > <Suspense fallback={<p className="muted">Loading topic…</p>}> <TopicDetails id={selectedId} /> </Suspense> </ErrorBoundary> </section> </div> ); }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: what you should have seen
  1. The box stays unticked, but Stats says 1 of 12 topics done.
  2. The filter is empty.
  3. The palette doesn't open the second time.
  4. The server timed out. again, every time.
Hint 2: where to look

toggleDone in store/progress.js; TabPanel in components/Tabs.jsx; how CommandPalette renders Dialog; and the Try again button in topics/TopicsPanel.jsx.

Show the four bugs and the fixed app
  1. The store changes its state in place (Day 2). toggleDone pushes onto state.done and returns the same object, so setState decides nothing changed and tells no subscriber. Stats only shows the right count because it mounts fresh. Return a new object: ({ done: [...state.done, id] }), or filter to remove.
  2. Hidden tabs are removed (Day 4). TabPanel returns null when it isn't selected, so the panel unmounts and loses its state. Wrap it in <Activity mode={selected === value ? "visible" : "hidden"}>.
  3. The dialog can't report that it closed (Day 5). Escape closes the native dialog, but without onClose the palette's open state is still true, so the next setOpen(true) changes nothing. Pass onClose={() => setOpen(false)}.
  4. Try again reuses the failed promise (Day 3). The cache still holds the rejected promise, so use throws the same error. Call invalidate(selectedId) before resetting.
Fixed: the Study Hub React · 20 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { lazy, Suspense, useState } from "react"; import CommandPalette from "./components/CommandPalette.jsx"; import { Tab, TabList, TabPanel, Tabs } from "./components/Tabs.jsx"; import FocusTimer from "./timer/FocusTimer.jsx"; import TopicsPanel from "./topics/TopicsPanel.jsx"; // A real build would download Stats as a separate chunk; the wait shows that. const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const StatsPanel = lazy(() => wait(600).then(() => import("./stats/StatsPanel.jsx"))); export default function App() { const [tab, setTab] = useState("topics"); const [status, setStatus] = useState(""); return ( <main> <header> <h1>Study Hub</h1> <CommandPalette onTab={setTab} onRun={(command) => setStatus(`Ran: ${command}`)} /> </header> <p className="muted" role="status">{status}</p> <Tabs value={tab} onChange={setTab}> <TabList label="Study Hub sections"> <Tab value="topics">Topics</Tab> <Tab value="timer">Focus timer</Tab> <Tab value="stats">Stats</Tab> </TabList> <TabPanel value="topics"><TopicsPanel /></TabPanel> <TabPanel value="timer"><FocusTimer /></TabPanel> <TabPanel value="stats"> <Suspense fallback={<p className="muted">Loading stats…</p>}> <StatsPanel /> </Suspense> </TabPanel> </Tabs> </main> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; } header { display: flex; justify-content: space-between; align-items: center; gap: 1rem; } kbd { font: 12px ui-monospace, monospace; border: 1px solid #c3ccd6; border-radius: 4px; padding: 0 0.3rem; } .topics { display: grid; grid-template-columns: 1fr 1.3fr; gap: 1rem; } .topics ul { list-style: none; padding: 0; margin: 0.5rem 0 0; } .topics li { display: flex; gap: 0.4rem; align-items: center; padding: 0.15rem 0; } .topics li button { border: 0; background: none; padding: 0.1rem 0.2rem; text-align: left; color: #06617f; } .topics li button[aria-current="true"] { font-weight: 700; } .pending { opacity: 0.6; } .bar { height: 0.5rem; border-radius: 999px; background: #e3e8ee; overflow: hidden; } .bar span { display: block; height: 100%; background: #087ea4; } .clock { font-size: 2rem; font-variant-numeric: tabular-nums; margin: 0.25rem 0 0.5rem; } import { useId, useState } from "react"; // A text box with a list of suggestions. Focus stays in the input; the // highlighted option is announced through aria-activedescendant. export default function Combobox({ label, options, onSelect }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); const id = useId(); const listId = `${id}-list`; const matches = options.filter((o) => o.toLowerCase().includes(query.trim().toLowerCase())); const optionId = (index) => `${id}-option-${index}`; function choose(option) { setQuery(option); setOpen(false); setActiveIndex(-1); onSelect(option); } function handleKeyDown(event) { if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActiveIndex((i) => Math.min(i + 1, matches.length - 1)); } else if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (event.key === "Enter" && open && activeIndex >= 0) { event.preventDefault(); choose(matches[activeIndex]); } else if (event.key === "Escape") { setOpen(false); setActiveIndex(-1); } } return ( <div> <label htmlFor={`${id}-input`}>{label}</label>{" "} <input id={`${id}-input`} role="combobox" aria-expanded={open} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined} value={query} onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }} onKeyDown={handleKeyDown} /> {open && matches.length > 0 && ( <ul role="listbox" id={listId} aria-label={label}> {matches.map((option, index) => ( <li key={option} id={optionId(index)} role="option" aria-selected={index === activeIndex} data-active={index === activeIndex} onMouseDown={(e) => e.preventDefault()} onClick={() => choose(option)} > {option} </li> ))} </ul> )} </div> ); } import { useEffect, useState } from "react"; import { resetProgress } from "../store/progress.js"; import { send } from "../store/timer.js"; import Combobox from "./Combobox.jsx"; import Dialog from "./Dialog.jsx"; // Every command is a name and what it does. The palette knows nothing else // about the app. function commandsFor(onTab) { return { "Go to Topics": () => onTab("topics"), "Go to Focus timer": () => onTab("timer"), "Go to Stats": () => onTab("stats"), "Start focus session": () => { send("START"); onTab("timer"); }, "Reset progress": () => resetProgress(), }; } export default function CommandPalette({ onTab, onRun }) { const [open, setOpen] = useState(false); const commands = commandsFor(onTab); // Ctrl+K or ⌘K opens the palette from anywhere on the page. useEffect(() => { function handleKeyDown(event) { if (event.key.toLowerCase() === "k" && (event.ctrlKey || event.metaKey)) { event.preventDefault(); setOpen(true); } } window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, []); function run(name) { setOpen(false); commands[name](); onRun(name); } return ( <> <button onClick={() => setOpen(true)}>Commands <kbd>Ctrl K</kbd></button> <Dialog open={open} onClose={() => setOpen(false)} title="Command palette"> {open && <Combobox label="Command" options={Object.keys(commands)} onSelect={run} />} </Dialog> </> ); } import { useEffect, useRef } from "react"; // The browser's own modal dialog: it moves focus inside, blocks the page // behind it, closes on Escape, and returns focus to whatever opened it. export default function Dialog({ open, onClose, title, children }) { const ref = useRef(null); // Keep the real <dialog> in step with the open prop. useEffect(() => { const dialog = ref.current; if (open && !dialog.open) dialog.showModal(); if (!open && dialog.open) dialog.close(); }, [open]); return ( <dialog ref={ref} onClose={onClose} aria-labelledby="dialog-title"> <h2 id="dialog-title">{title}</h2> {children} </dialog> ); } import { Component } from "react"; // Catches rendering errors below it and shows fallback(error, reset). // When resetKey changes, it clears the error without remounting its children, // so a Suspense boundary inside it keeps its content during a transition. export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidUpdate(previous) { if (this.state.error && previous.resetKey !== this.props.resetKey) this.reset(); } reset = () => this.setState({ error: null }); render() { if (this.state.error) return this.props.fallback(this.state.error, this.reset); return this.props.children; } } import { Activity, createContext, useContext, useId, useRef } from "react"; // Compound, controlled tabs (Day 1) with a roving tabindex (Day 5). Hidden // panels stay mounted inside <Activity> (Day 4), so they keep their state. const TabsContext = createContext(null); function useTabs(part) { const tabs = useContext(TabsContext); if (tabs === null) throw new Error(`<${part}> must be used inside <Tabs>.`); return tabs; } export function Tabs({ value, onChange, children }) { const baseId = useId(); return <TabsContext value={{ selected: value, select: onChange, baseId }}>{children}</TabsContext>; } export function TabList({ label, children }) { useTabs("TabList"); const listRef = useRef(null); function handleKeyDown(event) { const tabs = [...listRef.current.querySelectorAll('[role="tab"]')]; const index = tabs.indexOf(document.activeElement); const next = { ArrowRight: (index + 1) % tabs.length, ArrowLeft: (index - 1 + tabs.length) % tabs.length, Home: 0, End: tabs.length - 1, }[event.key]; if (next === undefined) return; event.preventDefault(); tabs[next].focus(); tabs[next].click(); } return ( <div role="tablist" aria-label={label} ref={listRef} onKeyDown={handleKeyDown}> {children} </div> ); } export function Tab({ value, children }) { const { selected, select, baseId } = useTabs("Tab"); const isSelected = selected === value; return ( <button role="tab" id={`${baseId}-tab-${value}`} aria-selected={isSelected} aria-controls={`${baseId}-panel-${value}`} tabIndex={isSelected ? 0 : -1} onClick={() => select(value)} > {children} </button> ); } export function TabPanel({ value, children }) { const { selected, baseId } = useTabs("TabPanel"); return ( <Activity mode={selected === value ? "visible" : "hidden"}> <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`} tabIndex={0}> {children} </div> </Activity> ); } import { topics } from "./topics.js"; const summaries = { 1: "Parts that share state through context, so users arrange them freely.", 2: "A value prop and an onChange, so the parent owns the state.", 3: "State outside React, read with useSyncExternalStore.", 4: "Every state lists the events it accepts, and where each leads.", 5: "Read a promise during render; a boundary shows the fallback.", 6: "Load a component's code only when it's first needed.", 7: "Measure with the Profiler before changing anything.", 8: "Render only the rows that are on screen.", 9: "showModal() handles focus, the backdrop and Escape.", 10: "Focus stays in the input; aria-activedescendant names the active option.", 11: "renderHook, rerender and fake timers.", 12: "vi.mock at the edges: the network, the clock, storage.", }; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); let windowingFailed = false; // A pretend server. Windowing fails the first time, so you can try the error // boundary's Try again. export async function fetchTopic(id) { console.log(`request: topic ${id}`); await wait(500); if (id === 8 && !windowingFailed) { windowingFailed = true; throw new Error("The server timed out."); } return { ...topics.find((t) => t.id === id), summary: summaries[id] }; } import { fetchTopic } from "./api.js"; // One promise per topic, reused on every render, as use() needs. const cache = new Map(); export function getTopic(id) { if (!cache.has(id)) cache.set(id, fetchTopic(id)); return cache.get(id); } export function invalidate(id) { cache.delete(id); } // Each day's topics. Details come from the pretend server in api.js. export const topics = [ { id: 1, day: 1, title: "Compound components" }, { id: 2, day: 1, title: "Controlled props" }, { id: 3, day: 2, title: "External stores" }, { id: 4, day: 2, title: "State machines" }, { id: 5, day: 3, title: "Suspense and use" }, { id: 6, day: 3, title: "Lazy loading" }, { id: 7, day: 4, title: "Profiling" }, { id: 8, day: 4, title: "Windowing" }, { id: 9, day: 5, title: "Dialogs" }, { id: 10, day: 5, title: "Comboboxes" }, { id: 11, day: 6, title: "Testing hooks" }, { id: 12, day: 6, title: "Mocking the server" }, ]; import { topics } from "../data/topics.js"; import { doneCount, progress } from "../store/progress.js"; import { timer } from "../store/timer.js"; import { useStore } from "../store/useStore.js"; export default function StatsPanel() { const done = useStore(progress, doneCount); const sessions = useStore(timer, (s) => s.sessions); const percent = Math.round((done / topics.length) * 100); return ( <section> <h2>{done} of {topics.length} topics done</h2> <div className="bar" role="progressbar" aria-label="Topics done" aria-valuenow={percent} aria-valuemin={0} aria-valuemax={100}> <span style={{ width: `${percent}%` }} /> </div> <p>Focus sessions finished: {sessions}</p> </section> ); } // The timer as a state machine: every state lists the events it accepts, and // where each one leads. Anything not listed is ignored. export const machine = { idle: { START: "focusing" }, focusing: { PAUSE: "paused", FINISH: "onBreak", RESET: "idle" }, paused: { RESUME: "focusing", RESET: "idle" }, onBreak: { FINISH: "idle", RESET: "idle" }, }; export function transition(status, event) { return machine[status][event] ?? status; } export function can(status, event) { return event in machine[status]; } import { createStore } from "./store.js"; // Which topics are done. Outside React, so the palette, the topic list and // the stats all share it without passing props. export const progress = createStore({ done: [] }); export function toggleDone(id) { progress.setState((state) => ({ done: state.done.includes(id) ? state.done.filter((d) => d !== id) : [...state.done, id], })); } export function resetProgress() { progress.setState({ done: [] }); } // Selectors return a number or a boolean, so components re-render only when // the answer changes. export const doneCount = (state) => state.done.length; export const isDone = (id) => (state) => state.done.includes(id); // A tiny store: state that lives outside React. Any code can read it, change // it, or subscribe to changes, including code that isn't a component. export function createStore(initialState) { let state = initialState; const listeners = new Set(); return { getState: () => state, setState(update) { const next = typeof update === "function" ? update(state) : update; if (Object.is(next, state)) return; state = next; listeners.forEach((listener) => listener()); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, }; } import { transition } from "./machine.js"; import { createStore } from "./store.js"; export const FOCUS_SECONDS = 25 * 60; export const timer = createStore({ status: "idle", remaining: FOCUS_SECONDS, sessions: 0 }); let ticker = null; export function send(event) { timer.setState((state) => { const status = transition(state.status, event); if (status === state.status) return state; const finishedFocus = state.status === "focusing" && status === "onBreak"; return { status, remaining: status === "idle" ? FOCUS_SECONDS : state.remaining, sessions: state.sessions + (finishedFocus ? 1 : 0), }; }); // The ticker runs only while focusing, outside React, so the timer keeps // going whichever tab is showing. const focusing = timer.getState().status === "focusing"; if (focusing && ticker === null) ticker = setInterval(tick, 1000); if (!focusing && ticker !== null) { clearInterval(ticker); ticker = null; } } function tick() { if (timer.getState().remaining <= 1) send("FINISH"); else timer.setState((state) => ({ ...state, remaining: state.remaining - 1 })); } import { useSyncExternalStore } from "react"; // Re-renders only when the selected part of the state changes. export function useStore(store, selector = (state) => state) { return useSyncExternalStore(store.subscribe, () => selector(store.getState())); } import { can } from "../store/machine.js"; import { send, timer } from "../store/timer.js"; import { useStore } from "../store/useStore.js"; const labels = { idle: "Ready", focusing: "Focusing", paused: "Paused", onBreak: "On a break" }; const clock = (s) => `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`; export default function FocusTimer() { const status = useStore(timer, (s) => s.status); const remaining = useStore(timer, (s) => s.remaining); return ( <section> <h2>{labels[status]}</h2> <p className="clock">{clock(remaining)}</p> <div className="toolbar"> {["START", "PAUSE", "RESUME", "FINISH", "RESET"].map((event) => ( <button key={event} onClick={() => send(event)} disabled={!can(status, event)}> {event[0] + event.slice(1).toLowerCase()} </button> ))} </div> </section> ); } import { use } from "react"; import { getTopic } from "../data/cache.js"; export default function TopicDetails({ id }) { const topic = use(getTopic(id)); return ( <article className="card"> <h2>{topic.title}</h2> <p className="muted">Day {topic.day}</p> <p>{topic.summary}</p> </article> ); } import { Suspense, useState, useTransition } from "react"; import ErrorBoundary from "../components/ErrorBoundary.jsx"; import { invalidate } from "../data/cache.js"; import { topics } from "../data/topics.js"; import { isDone, progress, toggleDone } from "../store/progress.js"; import { useStore } from "../store/useStore.js"; import TopicDetails from "./TopicDetails.jsx"; function TopicRow({ topic, selected, onSelect }) { const done = useStore(progress, isDone(topic.id)); return ( <li> <input type="checkbox" checked={done} onChange={() => toggleDone(topic.id)} aria-label={`${topic.title} done`} /> <button aria-current={selected} onClick={() => onSelect(topic.id)}>{topic.title}</button> </li> ); } export default function TopicsPanel() { const [filter, setFilter] = useState(""); const [selectedId, setSelectedId] = useState(1); const [attempt, setAttempt] = useState(0); const [isPending, startTransition] = useTransition(); const shown = topics.filter((t) => t.title.toLowerCase().includes(filter.trim().toLowerCase())); function select(id) { // Keep the current details on screen while the next ones load. startTransition(() => setSelectedId(id)); } return ( <div className="topics"> <section> <label> Filter <input value={filter} onChange={(e) => setFilter(e.target.value)} /> </label> <ul> {shown.map((t) => ( <TopicRow key={t.id} topic={t} selected={t.id === selectedId} onSelect={select} /> ))} </ul> </section> <section className={isPending ? "pending" : undefined}> <ErrorBoundary resetKey={`${selectedId}:${attempt}`} fallback={(error) => ( <div role="alert"> <p className="error">{error.message}</p> <button onClick={() => { invalidate(selectedId); setAttempt((a) => a + 1); }}>Try again</button> </div> )} > <Suspense fallback={<p className="muted">Loading topic…</p>}> <TopicDetails id={selectedId} /> </Suspense> </ErrorBoundary> </section> </div> ); }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Recall questions

Answer each in a sentence or two, then check the lesson it came from.

  1. How do you choose between value and defaultValue, and what goes wrong if a component switches modes while mounted? (Day 1)
  2. Why must a useSyncExternalStore selector not build a new object each time? (Day 2)
  3. Why does a promise passed to use need a cache? (Day 3)
  4. What does a transition change about how a Suspense fallback appears? (Day 3)
  5. What should you do before optimising a slow screen? (Day 4)
  6. What happens to a hidden Activity child's state and effects? (Day 4)
  7. Why does a combobox keep focus in its input? (Day 5)
  8. Why must a live region exist before its text changes? (Day 5)
  9. Why does a fake-timer test need one act per step? (Day 6)

Ready for the next step?

You're ready to move on if you can, without help:

  • design a component API with compound parts and controlled props
  • move shared state into a store, and read it with cheap selectors
  • load data with Suspense, and keep the screen steady with transitions
  • measure a slow screen, find the cause, and fix it
  • build a dialog and a combobox that work with only a keyboard
  • test hooks, timing and a server, and say what jsdom can't check

If one of these feels shaky, redo that day's checkpoint from scratch.

Was this article helpful?

Your response is saved on this device.