Skip to content

Extend It

The Course
•
20 min study

Each feature here goes through one part of the Study Hub: a command, a store selector, and a component that subscribes to exactly what it shows. Work in the lab below, or in your local project, where you can add a test for each one.

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.
Exercise

1. Pause or resume

Add a Pause or resume timer command to the palette: it pauses when the timer is focusing, and resumes otherwise.

Your working space 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.
Hint 1: the idea

An external-store command can inspect current state at the moment it runs. Hooks are only needed for rendering subscriptions.

Hint 2: a first step

A command runs outside rendering, so it can read the store directly with timer.getState(). No hook needed.

Show one solution

In CommandPalette.jsx:

JavaScript
import { send, timer } from "../store/timer.js";
JavaScript
"Pause or resume timer": () => send(timer.getState().status === "focusing" ? "PAUSE" : "RESUME"),

If the timer is idle, RESUME isn't accepted, so nothing happens: the state machine takes care of it.

Exercise

2. Progress per day

Under the bar in Stats, list each day's progress: Day 1: 0 of 2, Day 2: 1 of 2, and so on.

Your working space 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.
Hint 1: the idea

Select state.done, the array itself, and work out the per-day counts during render.

Hint 2: a first step

A selector that builds a new array or object, such as (s) => topics.filter((t) => s.done.includes(t.id)), returns a different value every time React asks. Try it: React reports The result of getSnapshot should be cached to avoid an infinite loop.

Show one solution

In StatsPanel.jsx, after percent:

JavaScript
const doneIds = useStore(progress, (s) => s.done);
const days = [1, 2, 3, 4, 5, 6].map((day) => {
  const ofDay = topics.filter((t) => t.day === day);
  return { day, total: ofDay.length, done: ofDay.filter((t) => doneIds.includes(t.id)).length };
});

and under the sessions line:

JSX
<ul>
  {days.map((d) => <li key={d.day}>Day {d.day}: {d.done} of {d.total}</li>)}
</ul>

s.done is the same array until progress changes, so it's safe to select.

Exercise

3. Time left on the tab

While a focus session runs, show the time left on the tab: Focus timer (24:58). Only the tab label should re-render each second, not App.

Your working space 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.
Hint 1: the idea

Write a TimeLeft component that subscribes to the timer, and render it inside the Tab. App itself doesn't read the timer, so it doesn't re-render.

Hint 2: a first step

Return null unless the status is focusing, so the label stays Focus timer at other times. Export clock from FocusTimer.jsx to format it.

Show one solution

In FocusTimer.jsx, add export in front of const clock. In App.jsx:

JavaScript
import FocusTimer, { clock } from "./timer/FocusTimer.jsx";
import { timer } from "./store/timer.js";
import { useStore } from "./store/useStore.js";

function TimeLeft() {
  const remaining = useStore(timer, (s) => (s.status === "focusing" ? s.remaining : null));
  return remaining === null ? null : ` (${clock(remaining)})`;
}
JSX
<Tab value="timer">Focus timer<TimeLeft /></Tab>

This is Day 4's lesson in a new form: put the subscription in the smallest component that shows the value.

Was this article helpful?

Your response is saved on this device.