Sub topic 9
Avoiding request waterfalls
This chapter assumes you can write a component that fetches in useEffect, track loading, error and success state, and clean up with AbortController. It also assumes you know the useFetch hook from the previous chapter. Here you will learn why requests that could run together end up running one after another, and how to fix it.
What a waterfall is
A request waterfall happens when request B does not start until request A has finished, even though B did not need A's result. In the browser's Network panel this shows up as a staircase: each bar starts where the previous one ends.
Some waterfalls are unavoidable. If you need a user's teamId before you can ask for the team, the second request has to wait. Many waterfalls are accidental, though. They come from how the code is structured, not from the data.
The cost adds up. Three requests of 300 ms each take about 900 ms in sequence and about 300 ms in parallel. The latency of each request is paid again for every step in the chain.
Waterfall 1: sequential awaits in one effect
The most direct cause is awaiting each request in turn inside one async function.
import { useEffect, useState } from 'react';
async function getJson(url, signal) {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
function Dashboard({ userId }) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
setState({ status: 'loading', data: null, error: null });
async function load() {
// Each await blocks the next request from starting.
const user = await getJson(`/api/users/${userId}`, signal);
const posts = await getJson(`/api/users/${userId}/posts`, signal);
const notifications = await getJson(`/api/users/${userId}/notifications`, signal);
setState({ status: 'success', data: { user, posts, notifications }, error: null });
}
load().catch((error) => {
if (error.name === 'AbortError') return;
setState({ status: 'error', data: null, error });
});
return () => controller.abort();
}, [userId]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>Error: {state.error.message}</p>;
const { user, posts, notifications } = state.data;
return (
<section>
<h1>{user.name}</h1>
<p>{posts.length} posts, {notifications.length} notifications</p>
</section>
);
}None of the three URLs uses the result of another, since all of them need only userId. Start the requests together and wait for all of them with Promise.all:
async function load() {
const [user, posts, notifications] = await Promise.all([
getJson(`/api/users/${userId}`, signal),
getJson(`/api/users/${userId}/posts`, signal),
getJson(`/api/users/${userId}/notifications`, signal),
]);
setState({ status: 'success', data: { user, posts, notifications }, error: null });
}Only the body of load changes. The cleanup, the abort check and the state shape stay the same. All three requests share one signal, so one controller.abort() cancels the whole group.
Behavior to know about Promise.all
- It rejects as soon as any promise rejects. One failed request puts the whole component into the error state, even if the other two succeeded.
- It resolves only when the slowest request finishes. The fast ones cannot render early.
- Use
Promise.allSettledif partial results are acceptable. It never rejects, and you check each result'sstatusyourself.
Waterfall 2: parent and child components
The second cause is harder to see because it is spread across files. A child component only starts fetching once it renders, and it only renders once the parent has stopped showing its loading state.
import { useFetch } from './useFetch';
function Profile({ userId }) {
const user = useFetch(`/api/users/${userId}`);
if (user.status === 'loading') return <p>Loading profile...</p>;
if (user.status === 'error') return <p>Error: {user.error.message}</p>;
return (
<section>
<h1>{user.data.name}</h1>
<Posts userId={userId} />
</section>
);
}
function Posts({ userId }) {
// This request cannot start until Profile has its data.
const posts = useFetch(`/api/users/${userId}/posts`);
if (posts.status === 'loading') return <p>Loading posts...</p>;
if (posts.status === 'error') return <p>Error: {posts.error.message}</p>;
return (
<ul>
{posts.data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}Posts needs only userId, which Profile already has as a prop. The early return in Profile stops Posts from mounting, and so its effect never runs. The two requests are chained by the rendering order and not by any data dependency.
There are two common fixes.
- Render the child earlier. Remove the early return so
Postsmounts in the first render. Each component then shows its own loading state, and both effects run in the same commit. - Lift the fetching up. Call both hooks at the top of
Profile, then pass the results down as props. Hooks always run before any early return, so both requests start at once.
function Profile({ userId }) {
const user = useFetch(`/api/users/${userId}`);
const posts = useFetch(`/api/users/${userId}/posts`);
if (user.status === 'loading') return <p>Loading profile...</p>;
if (user.status === 'error') return <p>Error: {user.error.message}</p>;
return (
<section>
<h1>{user.data.name}</h1>
<PostList posts={posts} />
</section>
);
}
function PostList({ posts }) {
if (posts.status === 'loading') return <p>Loading posts...</p>;
if (posts.status === 'error') return <p>Error: {posts.error.message}</p>;
return (
<ul>
{posts.data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}Comparing the fixes
| Approach | Total wait | Partial rendering | Cost |
|---|---|---|---|
| Sequential awaits | Sum of all requests | None | Simplest code, slowest |
| `Promise.all` in one effect | Slowest request | None | One failure fails the group |
| One hook per request, called together | Slowest request | Each section independently | Parent must know every child's data needs |
| Child fetches on its own, rendered early | Slowest request | Each section independently | Children stay self-contained, but you must not hide them behind a parent's loading state |
Lifting fetches into a parent trades locality for speed. The parent now has to know what each child needs. In a large tree, that coupling is what pushes teams toward query libraries and route-level data loading, which later chapters cover.
Dependent requests that are real
Sometimes the second URL does need the first response.
function TeamName({ userId }) {
const user = useFetch(`/api/users/${userId}`);
const teamUrl = user.status === 'success' ? `/api/teams/${user.data.teamId}` : null;
// useFetch from the previous chapter always fetches, so this chain needs
// a version that accepts null and skips the request.
// ...
}You cannot parallelize this on the client. You have three options:
- Change the API so one request returns what you need, for example
/api/users/42?include=team. This is the most effective fix, because it removes a network round trip. - Move the chain to the server, where both calls happen close to the data and the browser makes one request.
- Keep the chain, but make it visible in your loading UI so a second spinner does not look like a bug.
Other limits on parallel requests
Parallel is not always free.
- Browsers cap concurrent connections per host. HTTP/1.1 typically allows about six. HTTP/2 multiplexes many requests over one connection, which makes the cap less of a concern.
- Firing dozens of requests at once, for example one per list item, can overload a slow backend. Batch them into one request.
- A parallel group still waits on its slowest member. If one request takes five seconds,
Promise.allmakes the fast ones wait too.
Finding waterfalls
Open the browser's Network panel, reload, and read the Waterfall column. Look for requests whose start time equals the end time of an earlier request. Then ask whether the later request's URL or body used anything from the earlier response. If it did not, the chain is accidental. Trace it back to a sequential await or a component that mounts late.
Exercise
A Page component fetches /api/article/7, shows "Loading..." until it arrives, then renders <Comments articleId={7} />, which fetches /api/article/7/comments. The comments URL uses only the article ID, which is already known. Why is this a waterfall, and name two ways to remove it.
Show answer
Comments cannot mount until Page finishes loading the article, so the comments request starts only after the article request ends, although it does not need the article's data. Fix it by (1) rendering Comments in the first render, not behind the article's loading return, so both effects run in the same commit, or (2) calling both useFetch hooks at the top of Page and passing the comments result down as a prop. Starting both inside one effect with Promise.all also works.
Exercise
Your Promise.all dashboard shows an error page whenever the notifications endpoint fails, even though the user and posts loaded fine. What change keeps the working data visible?
Show answer
Replace Promise.all with Promise.allSettled and check each result's status. Store the fulfilled values and show an error only in the section whose request was rejected. Alternatively, use one hook per section so each request tracks its own state.