Skip to content

Lesson 36 of 37React at scale

Project: A Gym Workout Log

Build a workout log in React, stage by stage: components and props, a typed reducer with derived totals, an accessible add-set form, a rest timer hook with effect cleanup, history from a fake API with memo where it pays off, and Vitest tests you run locally.

17 min read0/5 questions

You have learned React one idea at a time. This project puts those ideas into one small app, in the order you would really reach for them at work. You will build a workout log: the screen a lifter keeps open between sets. It lists today's exercises and sets, adds new sets through a form, runs a rest timer after each set, and loads past training from a server.

It has numbers to validate, totals to compute, a clock that ticks on its own and a slow, long history. Each pushes you toward a different tool from the course.

Stages 1 to 5 are runnable blocks. Each is a complete app that repeats the code it needs from earlier stages, so you can run any of them alone. Stage 6 moves the code into a real Vite project and adds tests you run on your own machine.

The plan

Sketch the tree first and decide where each piece of state lives, as in Components and Props and Lifting State Up.

The workout log
App: workout reducerAppworkout reducerExerciseCard: one per exerciseExerciseCardone per exerciseAddSetForm: its own field stateAddSetFormits own field stateuseCountdown: effect with cleanupuseCountdowneffect with cleanupuseHistory: fake API, ignore flaguseHistoryfake API, ignore flagServer: past setsServerpast setspropsonAddstart, stopload, retryfetch

App owns the workout: exercises and sets, changed only through a reducer.

1/4

Three rules guide every stage:

  • One owner per piece of state. The workout lives in App. The text you are typing into a form lives in that form.
  • Compute what you can. Totals, counts and personal bests are derived during render, never stored next to the data they come from.
  • Effects only for the outside world. The timer and the server need effects. Nothing else does.

Stage 1: the screen as components

Start with static data and pure components. Panel takes children, so any card can share the same frame. ExerciseCard takes one exercise as a prop and renders its sets with map, keyed by set.id. Lists and Keys showed why the key must be a stable ID: in stage 2 you will remove sets from the middle, and an index key would move state onto the wrong row.

The empty case uses a ternary from Conditional Rendering. Note the set.done && <strong> pattern: it is safe because done is a boolean. If it were a number, a 0 would appear on screen.

ReactWorkoutLog.tsx
import type { ReactNode } from "react"; type WorkoutSet = { id: string; weightKg: number; reps: number; done: boolean };type Exercise = { id: string; name: string; sets: WorkoutSet[] }; const TODAY: Exercise[] = [ { id: "squat", name: "Back squat", sets: [ { id: "s1", weightKg: 60, reps: 8, done: true }, { id: "s2", weightKg: 70, reps: 6, done: true }, { id: "s3", weightKg: 70, reps: 6, done: false }, ], }, { id: "rdl", name: "Romanian deadlift", sets: [{ id: "s4", weightKg: 50, reps: 10, done: false }], }, { id: "lunge", name: "Walking lunge", sets: [] },]; // Volume = weight x reps, counted only for sets you finished.function volume(sets: WorkoutSet[]): number { return sets.filter((s) => s.done).reduce((sum, s) => sum + s.weightKg * s.reps, 0);} function Panel({ title, children }: { title: string; children: ReactNode }) { return ( <section style={{ border: "1px solid #ccc", padding: 12, marginBottom: 12 }}> <h2 style={{ margin: "0 0 8px", fontSize: 18 }}>{title}</h2> {children} </section> );} function SetRow({ index, set }: { index: number; set: WorkoutSet }) { return ( <li> Set {index + 1}: {set.weightKg} kg x {set.reps} {set.done && <strong> (done)</strong>} </li> );} function ExerciseCard({ exercise }: { exercise: Exercise }) { return ( <Panel title={exercise.name}> {exercise.sets.length === 0 ? ( <p>No sets yet.</p> ) : ( <ol> {exercise.sets.map((set, i) => ( <SetRow key={set.id} index={i} set={set} /> ))} </ol> )} <p>Volume: {volume(exercise.sets)} kg</p> </Panel> );} export default function App() { const total = TODAY.reduce((sum, ex) => sum + volume(ex.sets), 0); return ( <main> <h1 style={{ fontSize: 22 }}>Leg day</h1> <p>Total volume: {total} kg</p> {TODAY.map((ex) => ( <ExerciseCard key={ex.id} exercise={ex} /> ))} </main> );}

volume is a plain function, not a hook and not state, so you can call it for a card or for the whole workout. Change a done: false to true and both totals update.

Check: the header says 900 kg, the squat card says 900 kg, and the lunge card says "No sets yet."

Predict the outputJavaScript

What does this print?

const volume = (sets) =>
sets.filter((s) => s.done).reduce((sum, s) => sum + s.weightKg * s.reps, 0);

const sets = [
{ weightKg: 60, reps: 8, done: true },
{ weightKg: 70, reps: 6, done: false },
{ weightKg: 70, reps: 6, done: true },
];
const toggled = sets.map((s, i) => (i === 1 ? { ...s, done: !s.done } : s));
console.log(volume(sets), volume(toggled), sets[1].done);
Need a nudge? Hints walk you through it.

Stage 2: a reducer for the workout

Now the data must change. A lifter marks sets done, removes a mistake and repeats the last set. You could write three useState setters that each copy nested arrays, but the update logic would be scattered across event handlers. useReducer puts it in one pure function instead.

The actions are a discriminated union, as in React with TypeScript. Each one says what happened, such as set_toggled, not how to change the state. The default branch calls assertNever, so adding a fourth action without handling it is a compile error.

The reducer needs new IDs, but it must be pure, and StrictMode calls it twice in development to catch impurity. So instead of Math.random(), the next ID is part of the state.

ReactWorkoutReducer.tsx
import { useReducer } from "react"; type WorkoutSet = { id: string; weightKg: number; reps: number; done: boolean };type Exercise = { id: string; name: string; sets: WorkoutSet[] };type State = { exercises: Exercise[]; nextId: number }; type Action = | { type: "set_added"; exerciseId: string; weightKg: number; reps: number } | { type: "set_toggled"; exerciseId: string; setId: string } | { type: "set_removed"; exerciseId: string; setId: string }; function assertNever(value: never): never { throw new Error(`Unhandled action: ${JSON.stringify(value)}`);} // Change one exercise, keep the rest. Returns new arrays, never mutates.function updateExercise(state: State, id: string, change: (ex: Exercise) => Exercise): Exercise[] { return state.exercises.map((ex) => (ex.id === id ? change(ex) : ex));} function workoutReducer(state: State, action: Action): State { switch (action.type) { case "set_added": { const set = { id: `s${state.nextId}`, weightKg: action.weightKg, reps: action.reps, done: false }; return { nextId: state.nextId + 1, exercises: updateExercise(state, action.exerciseId, (ex) => ({ ...ex, sets: [...ex.sets, set] })), }; } case "set_toggled": return { ...state, exercises: updateExercise(state, action.exerciseId, (ex) => ({ ...ex, sets: ex.sets.map((s) => (s.id === action.setId ? { ...s, done: !s.done } : s)), })), }; case "set_removed": return { ...state, exercises: updateExercise(state, action.exerciseId, (ex) => ({ ...ex, sets: ex.sets.filter((s) => s.id !== action.setId), })), }; default: return assertNever(action); }} const INITIAL: State = { nextId: 5, exercises: [ { id: "squat", name: "Back squat", sets: [ { id: "s1", weightKg: 60, reps: 8, done: true }, { id: "s2", weightKg: 70, reps: 6, done: true }, { id: "s3", weightKg: 70, reps: 6, done: false }, ], }, { id: "rdl", name: "Romanian deadlift", sets: [{ id: "s4", weightKg: 50, reps: 10, done: false }] }, { id: "lunge", name: "Walking lunge", sets: [] }, ],}; function volume(sets: WorkoutSet[]): number { return sets.filter((s) => s.done).reduce((sum, s) => sum + s.weightKg * s.reps, 0);} export default function App() { const [state, dispatch] = useReducer(workoutReducer, INITIAL); // Derived during render: never stored, so never out of date. const allSets = state.exercises.flatMap((ex) => ex.sets); const doneCount = allSets.filter((s) => s.done).length; const total = state.exercises.reduce((sum, ex) => sum + volume(ex.sets), 0); return ( <main> <h1 style={{ fontSize: 22 }}>Leg day</h1> <p> {doneCount} of {allSets.length} sets done. Total volume: {total} kg </p> {state.exercises.map((ex) => { const last = ex.sets.at(-1); return ( <section key={ex.id} style={{ border: "1px solid #ccc", padding: 12, marginBottom: 12 }}> <h2 style={{ margin: "0 0 8px", fontSize: 18 }}>{ex.name}</h2> {ex.sets.length === 0 && <p>No sets yet.</p>} <ol> {ex.sets.map((set, i) => ( <li key={set.id}> {set.weightKg} kg x {set.reps}{" "} <button onClick={() => dispatch({ type: "set_toggled", exerciseId: ex.id, setId: set.id })}> {set.done ? "Undo" : "Done"} </button>{" "} <button aria-label={`Remove set ${i + 1} of ${ex.name}`} onClick={() => dispatch({ type: "set_removed", exerciseId: ex.id, setId: set.id })} > Remove </button> </li> ))} </ol> <button onClick={() => dispatch({ type: "set_added", exerciseId: ex.id, weightKg: last?.weightKg ?? 20, reps: last?.reps ?? 8 }) } > {last ? "Repeat last set" : "Add a 20 kg x 8 set"} </button> </section> ); })} </main> );}

Look at what is not in the state: the done count, the total set count and the total volume. All three are derived at the top of App. If you stored doneCount in state, every action would need to update it, and one day one would forget. Lifting State Up called this deriving instead of syncing.

updateExercise replaces only the matching exercise, so the others keep their old object references. That matters in stage 5, where memo compares references.

Check: press Done on the third squat set. The header changes to "3 of 4 sets done" and the total to 1320 kg. Press Remove on the first set, then Repeat last set, and the list still shows the right rows.

Stage 3: an accessible form for new sets

Lifters change the weight, so each card needs a small form. This is where Forms comes in, and where many apps fail keyboard and screen reader users.

The form follows the checklist from that lesson:

  • Every input has a visible <label> linked by htmlFor. The IDs come from useId, because there is one form per card and IDs must be unique on the page.
  • Errors are linked to their field with aria-describedby, and the field gets aria-invalid. A screen reader reads the message when focus reaches the input.
  • Focus moves to the first bad field on submit, using a ref from Refs. Without this, a keyboard user presses Enter and nothing seems to happen.
  • noValidate turns off the browser's own bubbles, so your messages are the only ones and they look the same everywhere.

The inputs are controlled and hold strings while you type. validate converts them to numbers once, in a pure function.

ReactAddSetForm.tsx
import { useId, useReducer, useRef, useState } from "react";import type { FormEvent } from "react"; type WorkoutSet = { id: string; weightKg: number; reps: number; done: boolean };type Exercise = { id: string; name: string; sets: WorkoutSet[] };type State = { exercises: Exercise[]; nextId: number };type Action = { type: "set_added"; exerciseId: string; weightKg: number; reps: number }; // The stage 2 reducer, cut down to the one action this stage needs.function workoutReducer(state: State, action: Action): State { const set = { id: `s${state.nextId}`, weightKg: action.weightKg, reps: action.reps, done: false }; return { nextId: state.nextId + 1, exercises: state.exercises.map((ex) => (ex.id === action.exerciseId ? { ...ex, sets: [...ex.sets, set] } : ex)), };} type Errors = { weight?: string; reps?: string }; // Pure validation: strings in, numbers or messages out.function validate(weight: string, reps: string): { errors: Errors; weightKg: number; reps: number } { const weightKg = Number(weight); const repCount = Number(reps); const errors: Errors = {}; if (weight.trim() === "" || !Number.isFinite(weightKg) || weightKg < 0 || weightKg > 500) { errors.weight = "Enter a weight from 0 to 500 kg."; } if (!Number.isInteger(repCount) || repCount < 1 || repCount > 100) { errors.reps = "Enter a whole number of reps from 1 to 100."; } return { errors, weightKg, reps: repCount };} function AddSetForm({ exerciseName, onAdd }: { exerciseName: string; onAdd: (weightKg: number, reps: number) => void }) { const id = useId(); const [weight, setWeight] = useState(""); const [reps, setReps] = useState(""); const [errors, setErrors] = useState<Errors>({}); const weightRef = useRef<HTMLInputElement>(null); const repsRef = useRef<HTMLInputElement>(null); function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const result = validate(weight, reps); setErrors(result.errors); // Move focus to the first bad field so keyboard and screen reader users land on it. if (result.errors.weight) { weightRef.current?.focus(); return; } if (result.errors.reps) { repsRef.current?.focus(); return; } onAdd(result.weightKg, result.reps); setReps(""); // keep the weight: the next set is usually the same repsRef.current?.focus(); } return ( <form onSubmit={handleSubmit} noValidate aria-label={`Add a set of ${exerciseName}`}> <div> <label htmlFor={`${id}-weight`}>Weight (kg)</label>{" "} <input ref={weightRef} id={`${id}-weight`} inputMode="decimal" value={weight} onChange={(e) => setWeight(e.target.value)} aria-invalid={errors.weight ? true : undefined} aria-describedby={errors.weight ? `${id}-weight-error` : undefined} /> {errors.weight && ( <p id={`${id}-weight-error`} style={{ color: "crimson", margin: "4px 0" }}> {errors.weight} </p> )} </div> <div> <label htmlFor={`${id}-reps`}>Reps</label>{" "} <input ref={repsRef} id={`${id}-reps`} inputMode="numeric" value={reps} onChange={(e) => setReps(e.target.value)} aria-invalid={errors.reps ? true : undefined} aria-describedby={errors.reps ? `${id}-reps-error` : undefined} /> {errors.reps && ( <p id={`${id}-reps-error`} style={{ color: "crimson", margin: "4px 0" }}> {errors.reps} </p> )} </div> <button type="submit">Add set</button> </form> );} const INITIAL: State = { nextId: 2, exercises: [ { id: "squat", name: "Back squat", sets: [{ id: "s1", weightKg: 60, reps: 8, done: true }] }, { id: "rdl", name: "Romanian deadlift", sets: [] }, ],}; export default function App() { const [state, dispatch] = useReducer(workoutReducer, INITIAL); return ( <main> {state.exercises.map((ex) => ( <section key={ex.id} style={{ border: "1px solid #ccc", padding: 12, marginBottom: 12 }}> <h2 style={{ margin: "0 0 8px", fontSize: 18 }}>{ex.name}</h2> {ex.sets.length === 0 ? ( <p>No sets yet.</p> ) : ( <ol> {ex.sets.map((s) => ( <li key={s.id}> {s.weightKg} kg x {s.reps} </li> ))} </ol> )} <AddSetForm exerciseName={ex.name} onAdd={(weightKg, reps) => dispatch({ type: "set_added", exerciseId: ex.id, weightKg, reps })} /> </section> ))} </main> );}

Each card has its own AddSetForm, and each form has its own state. Type a weight in the squat form and the deadlift form stays empty. That is "state belongs to each instance" from useState. The form does not know about the reducer at all. It calls onAdd with two numbers, and the parent decides what that means.

After a good submit, the form clears only the reps and moves focus back to that field, since the next set is usually the same weight.

Check: press Add set with both fields empty. The weight field shows its error and gets focus. Enter 70 and 6 and submit, and the set appears with the weight still filled in.

Quick check
Why does AddSetForm build its input IDs with useId instead of using a fixed ID such as weight?
Need a nudge? A hint rules out a wrong answer.

Stage 4: a rest timer with a custom hook

After a set you rest for a minute or two. The app should count that down. A clock is the outside world, so this is the job useEffect is for: start an interval when resting begins, and stop it when resting ends.

Two design choices make the timer correct:

  • Store when the rest ends, not how many seconds are left. A timer that does setRemaining((r) => r - 1) every second drifts, and browsers slow intervals down in background tabs. Storing endsAt and comparing it with the current time is always right, even if a tick arrives late.
  • The effect depends on isRunning, a boolean. It starts when rest starts. When the time passes, isRunning becomes false, React runs the cleanup, and the interval stops. Skipping and unmounting also run the cleanup, so no interval is ever left behind.

All of that lives in a custom hook, as Custom Hooks taught. The component calls useCountdown() and gets back remaining, isRunning, isFinished, start and stop. It never sees an interval ID. start and stop are wrapped in useCallback, so they keep the same identity across renders. You will need that in the next stage.

ReactRestTimer.tsx
import { useCallback, useEffect, useState } from "react"; // A countdown that survives slow ticks: it stores when rest ends, not how many seconds are left.function useCountdown() { const [endsAt, setEndsAt] = useState<number | null>(null); const [now, setNow] = useState(() => Date.now()); const isRunning = endsAt !== null && endsAt > now; const isFinished = endsAt !== null && !isRunning; const remaining = isRunning ? Math.ceil((endsAt - now) / 1000) : 0; useEffect(() => { if (!isRunning) return; // nothing to tick const id = setInterval(() => setNow(Date.now()), 250); return () => clearInterval(id); // runs when rest ends, on skip, and on unmount }, [isRunning]); // Stable functions, so memoized children that receive them do not re-render. const start = useCallback((seconds: number) => { const t = Date.now(); setNow(t); setEndsAt(t + seconds * 1000); }, []); const stop = useCallback(() => setEndsAt(null), []); return { remaining, isRunning, isFinished, start, stop };} function formatClock(seconds: number): string { const m = Math.floor(seconds / 60); const s = seconds % 60; return `${m}:${String(s).padStart(2, "0")}`;} type WorkoutSet = { id: string; label: string; done: boolean }; export default function App() { const timer = useCountdown(); const [sets, setSets] = useState<WorkoutSet[]>([ { id: "s1", label: "Back squat 70 kg x 6", done: false }, { id: "s2", label: "Back squat 70 kg x 6", done: false }, { id: "s3", label: "Back squat 70 kg x 6", done: false }, ]); function finishSet(id: string) { setSets((prev) => prev.map((s) => (s.id === id ? { ...s, done: true } : s))); timer.start(5); // 5 seconds so you can watch it end; use 90 in the gym } return ( <main> <h1 style={{ fontSize: 22 }}>Rest timer</h1> <ol> {sets.map((s) => ( <li key={s.id}> {s.label}{" "} {s.done ? <strong>done</strong> : <button onClick={() => finishSet(s.id)}>Finish set</button>} </li> ))} </ol> {timer.isRunning && ( <p> Resting: <span style={{ fontVariantNumeric: "tabular-nums", fontSize: 24 }}>{formatClock(timer.remaining)}</span>{" "} <button onClick={timer.stop}>Skip rest</button> </p> )} <div> <button onClick={() => timer.start(60)}>Rest 1:00</button> <button onClick={() => timer.start(90)}>Rest 1:30</button> </div> {/* Always in the page, so screen readers announce the text when it appears. */} <p role="status">{timer.isFinished ? "Rest over. Time for the next set." : ""}</p> </main> );}

The countdown itself is not announced to screen readers. A live region that changes four times a second would talk over everything. Instead, a role="status" element is always in the page, empty, and gets the text "Rest over" once. Live regions only announce changes, so the element must exist before the text arrives. Accessible Components: Portals, Focus and ARIA covered this pattern.

In development, StrictMode mounts, unmounts and mounts again. Without the return () => clearInterval(id), you would get two intervals and a clock that ticks twice as fast.

Check: press Finish set. The timer counts down from 0:05, then disappears, and "Rest over" appears. Start a 1:30 rest and press Skip rest: the timer stops at once.

Quick check
A teammate rewrites the timer as setInterval(() => setRemaining((r) => r - 1), 1000). It passes every test. What goes wrong in real use?
Need a nudge? A hint rules out a wrong answer.

Stage 5: history from a server, and memo where it pays

The last feature loads every set the lifter has logged and shows a best estimated one-rep max for each exercise. There is no real server here, so fetchHistory returns a Promise that settles after 800 ms using setTimeout. It fails on the first attempt on purpose, so you can see the error state and the Retry button.

The loading code follows Data Fetching:

  • One union for the result. Load is loading, error or success, never a mix of three booleans that can contradict each other.
  • An ignore flag in the cleanup. If the effect runs again before the old request returns, the old answer is dropped. That is the race-condition fix from useEffect, and StrictMode's double mount checks it for you.
  • A hook around it. useHistory returns load and retry, and the component never touches the Promise.

Then the performance problem. The rest timer sets state four times a second, so App re-renders four times a second while you rest. Without care, every one of those renders would rebuild a 1,500-row table and recompute the personal bests. Performance says to measure first, so the table logs each render to the console.

ReactTrainingHistory.tsx
import { memo, useCallback, useEffect, useMemo, useState } from "react"; type PastSet = { id: string; date: string; exercise: string; weightKg: number; reps: number }; const EXERCISES = ["Back squat", "Romanian deadlift", "Bench press", "Overhead press"]; // 1,500 made-up sets, the same every time (no Math.random).function makeHistory(count: number): PastSet[] { const start = Date.UTC(2026, 0, 1); return Array.from({ length: count }, (_, i) => ({ id: `h${i}`, date: new Date(start + Math.floor(i / 6) * 86_400_000).toISOString().slice(0, 10), exercise: EXERCISES[i % EXERCISES.length], weightKg: 40 + ((i * 7) % 50), reps: 3 + ((i * 5) % 8), }));} // A fake API. Attempt 0 fails so you can see the error state; Retry succeeds.function fetchHistory(attempt: number): Promise<PastSet[]> { return new Promise((resolve, reject) => { setTimeout(() => { if (attempt === 0) reject(new Error("Server unavailable (503)")); else resolve(makeHistory(1500)); }, 800); });} type Load = { status: "loading" } | { status: "error"; message: string } | { status: "success"; sets: PastSet[] }; function useHistory() { const [attempt, setAttempt] = useState(0); const [load, setLoad] = useState<Load>({ status: "loading" }); useEffect(() => { let ignore = false; // set by cleanup, so a stale answer is dropped fetchHistory(attempt).then( (sets) => { if (!ignore) setLoad({ status: "success", sets }); }, (error: unknown) => { if (!ignore) setLoad({ status: "error", message: error instanceof Error ? error.message : "Unknown error" }); }, ); return () => { ignore = true; }; }, [attempt]); const retry = useCallback(() => { setLoad({ status: "loading" }); setAttempt((a) => a + 1); }, []); return { load, retry };} // The stage 4 hook, unchanged.function useCountdown() { const [endsAt, setEndsAt] = useState<number | null>(null); const [now, setNow] = useState(() => Date.now()); const isRunning = endsAt !== null && endsAt > now; const remaining = isRunning ? Math.ceil((endsAt - now) / 1000) : 0; useEffect(() => { if (!isRunning) return; const id = setInterval(() => setNow(Date.now()), 250); return () => clearInterval(id); }, [isRunning]); const start = useCallback((seconds: number) => { const t = Date.now(); setNow(t); setEndsAt(t + seconds * 1000); }, []); return { remaining, isRunning, start };} // Estimated one-rep max (Epley formula), the usual way lifters compare sets.function bestByExercise(sets: PastSet[]): { exercise: string; best: number }[] { const best = new Map<string, number>(); for (const s of sets) { const e1rm = s.weightKg * (1 + s.reps / 30); best.set(s.exercise, Math.max(best.get(s.exercise) ?? 0, e1rm)); } return [...best].map(([exercise, value]) => ({ exercise, best: Math.round(value) }));} // memo: skip this render when `sets` is the same array as last time.const HistoryTable = memo(function HistoryTable({ sets }: { sets: PastSet[] }) { console.log(`HistoryTable rendered ${sets.length} rows`); return ( <div style={{ maxHeight: 220, overflow: "auto", border: "1px solid #ccc" }}> <table> <caption style={{ textAlign: "left" }}>Every set you have logged</caption> <thead> <tr> <th scope="col">Date</th> <th scope="col">Exercise</th> <th scope="col">Set</th> </tr> </thead> <tbody> {sets.map((s) => ( <tr key={s.id}> <td>{s.date}</td> <td>{s.exercise}</td> <td> {s.weightKg} kg x {s.reps} </td> </tr> ))} </tbody> </table> </div> );}); const EMPTY: PastSet[] = []; export default function App() { const { load, retry } = useHistory(); const timer = useCountdown(); // ticks 4 times a second while resting const sets = load.status === "success" ? load.sets : EMPTY; // Runs only when `sets` changes, not on every timer tick. const bests = useMemo(() => bestByExercise(sets), [sets]); return ( <main> <h1 style={{ fontSize: 22 }}>Training history</h1> <p> <button onClick={() => timer.start(10)}>Start a 10 second rest</button>{" "} {timer.isRunning && <span>Resting: {timer.remaining}s</span>} </p> {load.status === "loading" && <p>Loading your history...</p>} {load.status === "error" && ( <div role="alert"> <p>Could not load your history: {load.message}</p> <button onClick={retry}>Retry</button> </div> )} {load.status === "success" && ( <> <h2 style={{ fontSize: 18 }}>Best estimated one-rep max</h2> <ul> {bests.map((b) => ( <li key={b.exercise}> {b.exercise}: {b.best} kg </li> ))} </ul> <HistoryTable sets={load.sets} /> </> )} </main> );}

Two tools fix it, and both are justified here:

  • memo(HistoryTable) skips the table's render when its props are equal. Its only prop is load.sets, which keeps the same reference until a new request succeeds. Start a rest and the console stays quiet. Remove memo( and its closing parenthesis, start a rest, and the console fills with renders.
  • useMemo for the bests keeps bestByExercise from looping over 1,500 sets on every tick. It reruns only when sets changes. The EMPTY constant matters: an inline [] would be a new array each render and the memo would never hit.

Notice what made memo work: stable inputs. The table gets a reference that does not change, and the timer's start is a useCallback. If you passed sets={load.sets.filter(...)}, a new array every render, memo would compare, find a difference and render anyway.

A fix that needs no memo at all is to move the timer state down into a small component of its own, so the ticking never reaches the table. Try that first in your own code. Here several parts of App need the timer, so memo is the honest fix. The React Compiler, from Performance, can add this memoization for you.

Check: the error appears, then Retry loads the history and the bests. Start a rest and confirm the console shows no new table renders while the clock ticks.

Match the pairs0/5 matched

Match each part of the workout log to the tool that does the job.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps of pressing Retry in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Stage 6: a real project and tests

Now move the app out of the sandbox. Create a Vite project with the React and TypeScript template, as in Project Setup, and add the test tools from Testing React:

npm create vite@latest workout-log -- --template react-tscd workout-lognpm installnpm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom

Split the stages into files by feature. Export the reducer, its State type, AddSetForm and useCountdown so the tests can import them.

workout-log/src
  • src/
  • App.tsxthe page: reducer, cards, timer, history
  • test/
  • setup.tsjest-dom matchers and cleanup after each test
  • workout/
  • workoutReducer.tsState, Action, workoutReducer
  • workoutReducer.test.ts
  • AddSetForm.tsx
  • AddSetForm.test.tsx
  • useCountdown.ts
  • useCountdown.test.ts
  • useHistory.ts
  • HistoryTable.tsx

Add the test block to vite.config.ts that Testing React showed, with environment: "jsdom" and setupFiles: "./src/test/setup.ts", and the same setup.ts with its cleanup line (without it, the second form test finds two forms). Add a "test": "vitest" script in package.json. Config options change between versions, so check the Vitest docs if anything does not match.

The reducer is a pure function, so its tests need no rendering at all:

src/workout/workoutReducer.test.ts
import { expect, test } from "vitest";
import { workoutReducer, type State } from "./workoutReducer";
 
const start: State = {
  nextId: 2,
  exercises: [{ id: "squat", name: "Back squat", sets: [{ id: "s1", weightKg: 60, reps: 8, done: false }] }],
};
 
test("adding a set uses the next id and leaves the old state alone", () => {
  const next = workoutReducer(start, { type: "set_added", exerciseId: "squat", weightKg: 70, reps: 6 });
  expect(next.exercises[0].sets[1]).toEqual({ id: "s2", weightKg: 70, reps: 6, done: false });
  expect(next.nextId).toBe(3);
  expect(start.exercises[0].sets).toHaveLength(1);
});
 
test("toggling twice gets back to where you started", () => {
  const action = { type: "set_toggled", exerciseId: "squat", setId: "s1" } as const;
  const twice = workoutReducer(workoutReducer(start, action), action);
  expect(twice.exercises[0].sets[0].done).toBe(false);
});

The form tests act like a user, finding elements by role and label, never by class name. They also check the accessibility work from stage 3:

src/workout/AddSetForm.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test, vi } from "vitest";
import { AddSetForm } from "./AddSetForm";
 
test("an empty submit flags the weight and moves focus to it", async () => {
  const user = userEvent.setup();
  const onAdd = vi.fn();
  render(<AddSetForm exerciseName="Back squat" onAdd={onAdd} />);
 
  await user.click(screen.getByRole("button", { name: "Add set" }));
 
  const weight = screen.getByLabelText("Weight (kg)");
  expect(weight).toHaveAttribute("aria-invalid", "true");
  expect(weight).toHaveAccessibleDescription("Enter a weight from 0 to 500 kg.");
  expect(weight).toHaveFocus();
  expect(onAdd).not.toHaveBeenCalled();
});
 
test("a valid set is sent as numbers and the weight is kept", async () => {
  const user = userEvent.setup();
  const onAdd = vi.fn();
  render(<AddSetForm exerciseName="Back squat" onAdd={onAdd} />);
 
  await user.type(screen.getByLabelText("Weight (kg)"), "70");
  await user.type(screen.getByLabelText("Reps"), "6");
  await user.click(screen.getByRole("button", { name: "Add set" }));
 
  expect(onAdd).toHaveBeenCalledWith(70, 6);
  expect(screen.getByLabelText("Weight (kg)")).toHaveValue("70");
  expect(screen.getByLabelText("Reps")).toHaveValue("");
});

The timer hook is tested with renderHook and fake timers. Vitest's fake timers also control Date.now(), so ninety seconds pass instantly:

src/workout/useCountdown.test.ts
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { useCountdown } from "./useCountdown";
 
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
 
test("counts down and then reports that rest is over", () => {
  const { result } = renderHook(() => useCountdown());
 
  act(() => result.current.start(90));
  expect(result.current.remaining).toBe(90);
 
  act(() => vi.advanceTimersByTime(30_000));
  expect(result.current.remaining).toBe(60);
 
  act(() => vi.advanceTimersByTime(60_000));
  expect(result.current.isRunning).toBe(false);
  expect(result.current.isFinished).toBe(true);
});

Run them:

npx vitest run

You should see three files and five tests pass:

 ✓ src/workout/workoutReducer.test.ts (2 tests)
 ✓ src/workout/useCountdown.test.ts (1 test)
 ✓ src/workout/AddSetForm.test.tsx (2 tests)
 
 Test Files  3 passed (3)
      Tests  5 passed (5)

Check: break something on purpose. Remove the aria-describedby line from the weight input and the first form test fails with a clear message. Put it back. A test that cannot fail is not testing anything.

Make it yours

The core works. These would make it worth showing:

  • Persist the workout. Save the reducer state to localStorage through a useLocalStorage hook built on useSyncExternalStore, as in Custom Hooks, so a refresh does not lose today's sets.
  • A real backend. Replace fetchHistory with TanStack Query against a small API, as in Server State with TanStack Query, and make "Finish set" an optimistic mutation that rolls back on failure, as in Actions and Optimistic UI.
  • Virtualize the history. Five years of training is far more than 1,500 rows. Render only the visible rows, as Performance showed, and keep the table's caption and headers for screen readers.
  • Routes for past workouts. Add /workouts/:date with React Router so each session has a shareable URL, following Client-Side Routing.
  • End-to-end tests and deploy. Cover "log a set, rest, log another" with Playwright from Testing React, run it in CI and deploy the build.

When it is done, write it up with the Interview Prep lesson Writing Project Case Studies.

Build it for real in the Project Lab

  • Sticky notes, sorted is the same render-from-state loop in plain JavaScript, which makes what React does for you very clear.
  • Name my hamster practices the split between pure logic and the page, with a favourites list.
  • Snack match adds game rules, timers and a win state on top of state and rendering.
Key terms
derived state
A value such as a total or a count computed from existing state during render, instead of stored and kept in sync.
reducer
A pure function (state, action) => newState that holds all the update logic for one piece of state.
effect cleanup
The function an effect returns. React calls it before the effect runs again and on unmount, to stop timers, listeners or requests.
ignore flag
A local variable set to true in an effect's cleanup, so an async result from an outdated run is dropped instead of stored.
custom hook
A function whose name starts with use and which calls other hooks, so components can share stateful logic.
live region
An element, such as one with the status role, whose text changes are read aloud by screen readers without moving focus.
memo
A wrapper that skips a component's render when its props are equal by reference to the previous ones.

That is a workout log you could use in the gym tomorrow. The wrap-up next pulls the whole course together around one more realistic feature, from the first component to tested, debugged production code.