Part 11 / Topic 4 of 5
Avoiding waterfalls
A waterfall is two (or more) requests that do not actually depend on each other, coded so that one only starts after the previous one finishes - paying the cost of both, one after another, when nothing required that order. examples/04_avoiding_waterfalls.jsx's TripDashboardSequential fetches a profile, then - only inside that fetch's .then - fetches a train's live status, even though the train id is already a prop, not something the profile provides:
// examples/04_avoiding_waterfalls.jsx (waterfall)
export function TripDashboardSequential({ trainId }) {
const [profile, setProfile] = useState(null);
const [trainStatus, setTrainStatus] = useState(null);
useEffect(() => {
fetch("/api/profile")
.then((res) => res.json())
.then((p) => {
setProfile(p);
return fetch(`/api/trains/${trainId}/status`).then((res) => res.json());
})
.then(setTrainStatus);
}, [trainId]);
// ...
}
examples/04_avoiding_waterfalls.test.jsx does not measure wall-clock time to prove this (timing numbers would be marked (varies) and prove nothing repeatable) - it asserts how many requests have even started, which is deterministic. Right after mounting TripDashboardSequential, the mock fetch really has been called exactly once - the train-status request has not started at all yet, nested as it is inside the first request's callback. TripDashboardParallel starts both in the same tick instead, with Promise.all:
// examples/04_avoiding_waterfalls.jsx (parallel)
export function TripDashboardParallel({ trainId }) {
const [profile, setProfile] = useState(null);
const [trainStatus, setTrainStatus] = useState(null);
useEffect(() => {
Promise.all([
fetch("/api/profile").then((res) => res.json()),
fetch(`/api/trains/${trainId}/status`).then((res) => res.json()),
]).then(([p, status]) => { setProfile(p); setTrainStatus(status); });
}, [trainId]);
// ...
}
Right after mounting TripDashboardParallel, the mock fetch really has already been called twice - both requests, before either has resolved. Resolving the slower one first (on purpose, in the test) still produces the correct final screen, because Promise.all does not care which settles first, only that both eventually do.
Done here? The practice set for Part 11 — including the solutions — is on the part page.