Skip to content

The Study Board

The Course
•
20 min study

Today the week comes together. You'll read the finished Study Board, add an error boundary, run and test it on your own computer, extend it, and then build a different app from a brief.

Study Board React · 15 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import AddCardForm from "./components/AddCardForm.jsx"; import Board from "./components/Board.jsx"; import CardDetails from "./components/CardDetails.jsx"; import Toolbar from "./components/Toolbar.jsx"; import { BoardProvider } from "./state/BoardContext.jsx"; export default function App() { return ( <BoardProvider> <StudyBoard /> </BoardProvider> ); } function StudyBoard() { const [query, setQuery] = useState(""); const [selectedId, setSelectedId] = useState(null); return ( <main> <h1>Study Board</h1> <Toolbar query={query} onQueryChange={setQuery} /> <AddCardForm /> <Board query={query} selectedId={selectedId} onSelect={setSelectedId} /> <CardDetails selectedId={selectedId} onClose={() => setSelectedId(null)} /> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; 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; } import { useRef, useState } from "react"; import Field from "./Field.jsx"; import { useBoardDispatch } from "../state/BoardContext.jsx"; export default function AddCardForm() { const dispatch = useBoardDispatch(); const [title, setTitle] = useState(""); const [minutes, setMinutes] = useState("15"); const [errors, setErrors] = useState({}); const titleRef = useRef(null); const minutesRef = useRef(null); function handleSubmit(event) { event.preventDefault(); const amount = Number(minutes); const found = {}; if (title.trim() === "") found.title = "Enter a title."; if (!Number.isInteger(amount) || amount <= 0) found.minutes = "Enter whole minutes above 0."; setErrors(found); if (found.title) return titleRef.current.focus(); if (found.minutes) return minutesRef.current.focus(); dispatch({ type: "card_added", id: Date.now(), title: title.trim(), minutes: amount }); setTitle(""); titleRef.current.focus(); } return ( <form className="toolbar" onSubmit={handleSubmit} noValidate> <Field ref={titleRef} label="Title" value={title} onChange={setTitle} error={errors.title} /> <Field ref={minutesRef} label="Minutes" type="number" value={minutes} onChange={setMinutes} error={errors.minutes} /> <button type="submit">Add card</button> </form> ); } import Column from "./Column.jsx"; import ErrorBoundary from "./ErrorBoundary.jsx"; import { useCards } from "../state/BoardContext.jsx"; import { columns } from "../data.js"; export default function Board({ query, selectedId, onSelect }) { const cards = useCards(); const needle = query.trim().toLowerCase(); const visible = cards.filter((card) => card.title.toLowerCase().includes(needle)); return ( <div className="board"> {columns.map((column, index) => ( <ErrorBoundary key={column.id} fallback={<p className="column error">{column.title} couldn't be shown.</p>}> <Column column={column} next={columns[index + 1]} cards={visible.filter((card) => card.column === column.id)} selectedId={selectedId} onSelect={onSelect} /> </ErrorBoundary> ))} </div> ); } import { useState } from "react"; import { useBoardDispatch, useCards } from "../state/BoardContext.jsx"; import { columns } from "../data.js"; export default function CardDetails({ selectedId, onClose }) { const cards = useCards(); const card = cards.find((c) => c.id === selectedId); if (!card) return null; // A new card gets a fresh editor, so its draft starts from its own title. return <Editor key={card.id} card={card} onClose={onClose} />; } function Editor({ card, onClose }) { const dispatch = useBoardDispatch(); const [draft, setDraft] = useState(card.title); const column = columns.find((c) => c.id === card.column); return ( <section className="panel"> <h2>{card.title}</h2> <p className="muted">{column.title} · {card.minutes} minutes</p> <input aria-label="Rename" value={draft} onChange={(e) => setDraft(e.target.value)} />{" "} <button onClick={() => dispatch({ type: "card_renamed", id: card.id, title: draft.trim() })} disabled={draft.trim() === ""}> Rename </button>{" "} <button onClick={onClose}>Close</button> </section> ); } import { useBoardDispatch } from "../state/BoardContext.jsx"; export default function CardItem({ card, next, selected, onSelect }) { const dispatch = useBoardDispatch(); return ( <li className={selected ? "card selected" : "card"}> <button className="title" onClick={() => onSelect(card.id)}>{card.title}</button> <div className="muted">{card.minutes} min</div> {next && ( <button onClick={() => dispatch({ type: "card_moved", id: card.id, column: next.id })} aria-label={`Move ${card.title} to ${next.title}`}>→</button> )}{" "} <button onClick={() => dispatch({ type: "card_removed", id: card.id })} aria-label={`Remove ${card.title}`}>×</button> </li> ); } import { memo } from "react"; import CardItem from "./CardItem.jsx"; function Column({ column, next, cards, selectedId, onSelect }) { return ( <section className="column"> <h2> {column.title} <span className="count">({cards.length})</span> </h2> <ul className="cards"> {cards.map((card) => ( <CardItem key={card.id} card={card} next={next} selected={card.id === selectedId} onSelect={onSelect} /> ))} </ul> </section> ); } export default memo(Column); import { Component } from "react"; // Shows `fallback` instead of its children when rendering them throws. // Error boundaries are still written as classes: there's no hook for this. export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidCatch(error, info) { console.log("Caught by a boundary:", error.message); } render() { if (this.state.error) return this.props.fallback; return this.props.children; } } import { useId } from "react"; export default function Field({ ref, label, value, onChange, error, type = "text" }) { const id = useId(); const errorId = `${id}-error`; return ( <span> <label htmlFor={id}>{label}</label>{" "} <input ref={ref} id={id} type={type} value={value} onChange={(e) => onChange(e.target.value)} aria-invalid={error ? true : undefined} aria-describedby={error ? errorId : undefined} style={type === "number" ? { width: "4.5rem" } : undefined} /> {error && <span id={errorId} className="error"> {error}</span>} </span> ); } import { useBoardStats } from "../hooks/useBoardStats.js"; export default function Toolbar({ query, onQueryChange }) { const { total, done, minutesLeft } = useBoardStats(); return ( <div className="toolbar"> <input aria-label="Search cards" placeholder="Search cards" value={query} onChange={(e) => onQueryChange(e.target.value)} /> <span className="muted">{done} of {total} done · {minutesLeft} min left</span> </div> ); } import { useCards } from "../state/BoardContext.jsx"; // Counts worked out from the cards on every render: never stored. export function useBoardStats() { const cards = useCards(); const open = cards.filter((card) => card.column !== "done"); return { total: cards.length, done: cards.length - open.length, minutesLeft: open.reduce((sum, card) => sum + card.minutes, 0), }; } import { createContext, useContext, useReducer } from "react"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "../data.js"; const CardsContext = createContext(null); const DispatchContext = createContext(null); export function BoardProvider({ children, initialCards = starterCards }) { const [cards, dispatch] = useReducer(boardReducer, initialCards); return ( <CardsContext value={cards}> <DispatchContext value={dispatch}>{children}</DispatchContext> </CardsContext> ); } export function useCards() { const cards = useContext(CardsContext); if (cards === null) throw new Error("useCards must be used inside <BoardProvider>."); return cards; } export function useBoardDispatch() { const dispatch = useContext(DispatchContext); if (dispatch === null) throw new Error("useBoardDispatch must be used inside <BoardProvider>."); return dispatch; } // Every change to the cards. Pure: ids and times come in with the action. export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card)); case "card_renamed": return cards.map((card) => (card.id === action.id ? { ...card, title: action.title } : card)); case "card_removed": return cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Use it first: add a card, try a blank title, move cards along, select one and rename it, and search.

Where everything lives

The app is organised by role, as most real React projects are:

FolderHolds
state/The reducer and the context that serves it
hooks/Custom hooks
components/Everything that renders

A tour, day by day

Open the files in this order, and find each idea before reading its explanation.

DayIdeaWhere
1The selection is an id, not a copied cardStudyBoard in App.jsx
1Counts and the search results are computed, not storeduseBoardStats.js, Board.jsx
1Each card gets a fresh editor through a keyCardDetails.jsx
2Every change goes through one reducerstate/boardReducer.js
3The reducer is served through two contexts with checked hooksstate/BoardContext.jsx
4The form focuses the first problem and returns focus after adding; useId connects labels and errorsAddCardForm.jsx, Field.jsx
5A custom hook reads the context and works out the statshooks/useBoardStats.js
6Column is wrapped in memo with a stable onSelect, but it never skips a render here: question 3 below asks whyColumn.jsx, Board.jsx
7An error boundary around each columnErrorBoundary.jsx, Board.jsx: the next lesson

Two design choices to notice

App and StudyBoard are separate components. App only places the provider. StudyBoard holds the search and selection state, which isn't board data, so it stays local rather than going into the reducer. Not everything belongs in context:

JSX
export default function App() {
  return (
    <BoardProvider>
      <StudyBoard />
    </BoardProvider>
  );
}

function StudyBoard() {
  const [query, setQuery] = useState("");
  const [selectedId, setSelectedId] = useState(null);

  return (
    <main>
      <h1>Study Board</h1>
      <Toolbar query={query} onQueryChange={setQuery} />
      <AddCardForm />
      <Board query={query} selectedId={selectedId} onSelect={setSelectedId} />
      <CardDetails selectedId={selectedId} onClose={() => setSelectedId(null)} />
    </main>
  );
}

BoardProvider takes initialCards. The app never passes it, so it uses the starter cards. Tests pass their own cards, so each test starts from a known board. You'll use this in the Project Tests lesson:

JSX
export function BoardProvider({ children, initialCards = starterCards }) {
  const [cards, dispatch] = useReducer(boardReducer, initialCards);
  return (
    <CardsContext value={cards}>
      <DispatchContext value={dispatch}>{children}</DispatchContext>
    </CardsContext>
  );
}

Predict

  1. You select Try context, then search for draw. The selected card is hidden by the search. Does the details panel still show it?
  2. Rename Try context to Use context. Which components re-render?
  3. Add console.log("Column rendered", column.title); to Column, then click a card in Doing to select it. Column is wrapped in memo, and To do and Done didn't change. How many lines appear?
Check your predictions
  1. Yes. CardDetails looks the card up in all the cards by its id, not in the search results. The selection and the search are separate pieces of state, and neither depends on the other:

    JavaScript
    const cards = useCards();
    const card = cards.find((c) => c.id === selectedId);
  2. Everything reading useCards(): Board, CardDetails and Toolbar, through useBoardStats. AddCardForm doesn't, because it only reads the dispatch context, which never changes. All three columns re-render too, including Doing and Done, whose cards didn't change. Question 3 shows why.

  3. Three: Column rendered To do, Doing and Done. memo skips a render only when every prop is the same as last time. Two props never are. Board builds visible.filter(...) for each column on every render, and a new array is a changed prop, even with the same cards in it. And selectedId goes to every column, so a new selection changes all three. Since Board only re-renders when the cards, the search or the selection change, memo(Column) never skips anything here.

    It's a realistic mistake: memo looks like it helps, and only a measurement shows that it doesn't. To make it work, each column would need an array that stays the same while its cards do (useMemo per column) and a prop that only changes when its own card is selected, such as selectedId only for the column that holds it. For three short columns, that's more code than the renders cost. The honest fix is to remove memo, and add it back only when the Profiler shows the columns are slow.

Was this article helpful?

Your response is saved on this device.