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.
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.
App owns the workout: exercises and sets, changed only through a reducer.
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.
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."
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);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.
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 byhtmlFor. The IDs come fromuseId, 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 getsaria-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.
noValidateturns 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.
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.
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. StoringendsAtand 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,isRunningbecomes 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.
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.
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.
Loadis 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.
useHistoryreturnsloadandretry, 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.
Two tools fix it, and both are justified here:
memo(HistoryTable)skips the table's render when its props are equal. Its only prop isload.sets, which keeps the same reference until a new request succeeds. Start a rest and the console stays quiet. Removememo(and its closing parenthesis, start a rest, and the console fills with renders.useMemofor the bests keepsbestByExercisefrom looping over 1,500 sets on every tick. It reruns only whensetschanges. TheEMPTYconstant 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 each part of the workout log to the tool that does the job.
Put the steps of pressing Retry in order.
- Tap the steps below in the right order.
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-domSplit the stages into files by feature. Export the reducer, its State type, AddSetForm and useCountdown so the tests can import them.
- 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:
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:
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:
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 runYou 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
localStoragethrough auseLocalStoragehook built onuseSyncExternalStore, as in Custom Hooks, so a refresh does not lose today's sets. - A real backend. Replace
fetchHistorywith 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/:datewith 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.
- 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) => newStatethat 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.