Sub topic 9
Avoiding request waterfalls
This chapter assumes you can write a component that fetches in useEffect, you understand the dependency array, and you have seen the useFetch hook from the previous chapter. It covers how nested components can slow data loading, and how to fix it.
What a waterfall is
A request waterfall happens when one request cannot start until another has finished. Each request waits for the one before it, so the total time is the sum of all the delays.
Some waterfalls are unavoidable. If you need a user's ID before you can ask for their posts, the second request depends on the first. The problem is the waterfalls that exist only because of how the components are arranged.
How components create waterfalls
React renders a child only after its parent renders, and a parent that returns early for loading never renders its children. Effects run after render. Put these together and you get this:
import { useFetch } from './useFetch';
function Dashboard() {
const user = useFetch('/api/user');
if (user.status === 'loading') return <p>Loading user...</p>;
if (user.status === 'error') return <p>Error: {user.error.message}</p>;
return (
<>
<h1>{user.data.name}</h1>
<Notifications />
</>
);
}
function Notifications() {
const items = useFetch('/api/notifications');
if (items.status === 'loading') return <p>Loading notifications...</p>;
if (items.status === 'error') return <p>Error: {items.error.message}</p>;
return <p>{items.data.length} new notifications</p>;
}Notifications does not depend on the user data. But it is not rendered until Dashboard finishes loading, so its effect does not run until then.
If each request takes 300 ms, the page needs 600 ms. Started together, both would finish in about 300 ms.
Fix 1: start independent requests together
When the requests do not depend on each other, call both hooks in the same component, or in a common parent, so both effects run on the first render.
import { useFetch } from './useFetch';
function Dashboard() {
const user = useFetch('/api/user');
const notifications = useFetch('/api/notifications');
if (user.status === 'loading' || notifications.status === 'loading') {
return <p>Loading...</p>;
}
if (user.status === 'error') return <p>Error: {user.error.message}</p>;
if (notifications.status === 'error') {
return <p>Error: {notifications.error.message}</p>;
}
return (
<>
<h1>{user.data.name}</h1>
<p>{notifications.data.length} new notifications</p>
</>
);
}Both effects run after the first render, so the requests overlap. This is the same idea as Promise.all for plain promises.
Fix 2: don't block the whole page
Hoisting every request into one parent makes the page wait for the slowest one. Instead, render the parts that are ready and show a placeholder for the rest. Keep each fetch in a component that is rendered immediately, and avoid early returns in a parent that hide children needing their own data.
Dependent requests
When a request truly needs a value from an earlier one, pass that value as an input and skip the request until it exists. The useFetch hook from the previous chapter has no skip option, so this sketch shows the idea with a plain effect.
import { useEffect, useState } from 'react';
function UserPosts({ user }) {
const [posts, setPosts] = useState(null);
useEffect(() => {
if (!user) return;
const controller = new AbortController();
fetch(`/api/users/${user.id}/posts`, { signal: controller.signal })
.then((response) => response.json())
.then(setPosts)
.catch((err) => {
if (err.name !== 'AbortError') console.error(err);
});
return () => controller.abort();
}, [user]);
return posts ? <p>{posts.length} posts</p> : <p>Loading posts...</p>;
}A better fix is often on the server. A single endpoint such as /api/users/1/with-posts removes the second round trip.
Summary of options
| Situation | Approach |
|---|---|
| Requests are independent | Start them in the same component or a common parent |
| Request needs an earlier result | Skip until the value exists, or add a combined endpoint |
| Page has slow and fast parts | Let each part fetch and render on its own |
Exercise
A page renders <Profile />, which fetches /api/profile and returns "Loading..." until it arrives. After loading, it renders <Friends />, which fetches /api/friends and does not use any profile data. Each request takes 400 ms. How long does the page take to show everything, and how would you reduce it?
Show answer
About 800 ms, because Friends is not rendered until Profile finishes loading, so its request starts late. Start /api/friends earlier by fetching it in a parent that renders both components at once, or by rendering Friends outside the loading branch. Both requests then overlap and the page takes about 400 ms.