Skip to content

On Your Own: Flashcard Drill

The Course
•
25 min study

This is the course's final check: a different app, from a brief, with no walkthrough. Plan first: sketch the components, list the states and events, and decide what loads where. Then build one working step at a time. api.js is the pretend server; Dialog.jsx and ErrorBoundary.jsx are from earlier days.

Treat the suggested time as a first attempt, not a deadline. If the whole brief is too much for one sitting, first get one complete interaction working, then return for validation and the remaining cases. Before opening the solution, write down what works, what fails, and the next change you would try.

The brief

A Flashcard Drill: go through a deck, reveal each answer, and grade yourself.

Data

  • Load the deck with fetchDeck() from api.js, read with use, cached so it's requested once. Show Loading deck… while it loads, and an error boundary around the drill.

The drill

  • The drill is a state machine with three statuses: question accepts REVEAL; answer accepts GOT_IT and AGAIN; finished accepts RESTART. Anything else is ignored.
  • The screen shows Card 1 of 4, the question, and after REVEAL the answer.
  • Three buttons, Show answer, Got it and Again, each disabled when the current status doesn't accept its event.
  • Keys S, G and A do the same as the buttons, from anywhere on the page.
  • Score: 2 in a status message that screen readers announce. Got it adds a point.
  • After the last card, a dialog titled Drill finished says You got 3 of 4. with a Start again button. Start again, or Escape, starts over.

Acceptance checks:

  • Pressing G before the answer shows does nothing.
  • With the keyboard only: S, G, S, A, S, G, S, G gives You got 3 of 4., and focus is on Start again.
  • Escape closes it, and the drill is back on Card 1 of 4 with Score: 0.
  • No errors or warnings in the console.
Your workspace React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server with one deck of flashcards. const deck = [ { id: 1, question: "Which hook reads an external store?", answer: "useSyncExternalStore" }, { id: 2, question: "What does use() do with a pending promise?", answer: "Suspends until it settles" }, { id: 3, question: "Which element has tabIndex 0 in a roving tabindex?", answer: "The current one" }, { id: 4, question: "What keeps a hidden component's state?", answer: "<Activity mode=\"hidden\">" }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchDeck() { console.log("request: deck"); await wait(500); return deck; } // Build the Flashcard Drill here. api.js is the pretend server, and // Dialog.jsx and ErrorBoundary.jsx are from earlier days. See the brief. export default function App() { return ( <main> <h1>Flashcard Drill</h1> </main> ); } 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; } } 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; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: a plan

Files: cache.js for the deck promise, machine.js for the reducer, and Drill.jsx for the screen. App holds the boundary and Suspense. State: the status, the card index and the score, all in one useReducer.

Hint 2: the machine

Write the accepted events as data: { question: ["REVEAL"], answer: ["GOT_IT", "AGAIN"], finished: ["RESTART"] }. One can(state, type) function then serves both the reducer and the buttons' disabled.

Hint 3: knowing the last card

The reducer doesn't know the deck. Send the deck's length with the event: dispatch({ type: "GOT_IT", total: deck.length }).

Show one solution
One solution React · 9 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server with one deck of flashcards. const deck = [ { id: 1, question: "Which hook reads an external store?", answer: "useSyncExternalStore" }, { id: 2, question: "What does use() do with a pending promise?", answer: "Suspends until it settles" }, { id: 3, question: "Which element has tabIndex 0 in a roving tabindex?", answer: "The current one" }, { id: 4, question: "What keeps a hidden component's state?", answer: "<Activity mode=\"hidden\">" }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchDeck() { console.log("request: deck"); await wait(500); return deck; } import { Suspense } from "react"; import Drill from "./Drill.jsx"; import ErrorBoundary from "./ErrorBoundary.jsx"; export default function App() { return ( <main> <h1>Flashcard Drill</h1> <ErrorBoundary fallback={(error) => <p className="error" role="alert">{error.message}</p>}> <Suspense fallback={<p className="muted">Loading deck…</p>}> <Drill /> </Suspense> </ErrorBoundary> </main> ); } import { fetchDeck } from "./api.js"; // One promise, reused on every render, as use() needs. let deck = null; export function getDeck() { deck ??= fetchDeck(); return deck; } 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 { use, useEffect, useReducer } from "react"; import { getDeck } from "./cache.js"; import Dialog from "./Dialog.jsx"; import { can, drillReducer, initialDrill } from "./machine.js"; const keys = { s: "REVEAL", g: "GOT_IT", a: "AGAIN" }; export default function Drill() { const deck = use(getDeck()); const [drill, dispatch] = useReducer(drillReducer, initialDrill); const send = (type) => dispatch({ type, total: deck.length }); const card = deck[drill.index]; // S, G and A work anywhere on the page. The reducer ignores keys the // current status doesn't accept. useEffect(() => { function handleKeyDown(event) { const type = keys[event.key.toLowerCase()]; if (type && !event.ctrlKey && !event.metaKey) dispatch({ type, total: deck.length }); } window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, [deck.length]); return ( <section> {card && ( <article className="card"> <h2>Card {drill.index + 1} of {deck.length}</h2> <p>{card.question}</p> {drill.status === "answer" && <p><strong>{card.answer}</strong></p>} </article> )} <div className="toolbar"> <button onClick={() => send("REVEAL")} disabled={!can(drill, "REVEAL")}>Show answer <kbd>S</kbd></button> <button onClick={() => send("GOT_IT")} disabled={!can(drill, "GOT_IT")}>Got it <kbd>G</kbd></button> <button onClick={() => send("AGAIN")} disabled={!can(drill, "AGAIN")}>Again <kbd>A</kbd></button> </div> <p className="muted" role="status">Score: {drill.score}</p> <Dialog open={drill.status === "finished"} onClose={() => send("RESTART")} title="Drill finished"> <p>You got {drill.score} of {deck.length}.</p> <button onClick={() => send("RESTART")}>Start again</button> </Dialog> </section> ); } 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; } } // The drill as a state machine. Each status lists the events it accepts; // anything else is ignored. const accepts = { question: ["REVEAL"], answer: ["GOT_IT", "AGAIN"], finished: ["RESTART"], }; export const initialDrill = { status: "question", index: 0, score: 0 }; export function can(state, type) { return accepts[state.status].includes(type); } export function drillReducer(state, event) { if (!can(state, event.type)) return state; switch (event.type) { case "REVEAL": return { ...state, status: "answer" }; case "GOT_IT": case "AGAIN": { const index = state.index + 1; const score = state.score + (event.type === "GOT_IT" ? 1 : 0); return { status: index === event.total ? "finished" : "question", index, score }; } case "RESTART": return initialDrill; } } 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; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Your structure can differ. What matters is that the rules live in one place, that the deck loads once, and that the acceptance checks pass.

What next

You can now design components other people use, manage state inside and outside React, load data and code with Suspense, measure and fix performance, build accessible widgets, and test all of it. From here:

  • Download the drill and test it as you did the Study Hub: the machine as plain tests, the screen with a mocked api.js.
  • Read React's reference on react.dev, especially the pages for use, useSyncExternalStore and Activity.
  • Read the ARIA Authoring Practices Guide patterns before building your next widget.
  • Build something of your own, and start with the questions from this week: where does each piece of state live, what can be measured, and how will a keyboard user get through it?

Was this article helpful?

Your response is saved on this device.