DEV Community

Richard Oliver Bray
Richard Oliver Bray

Posted on

Understanding and Preventing Fetch Waterfalls in React

If you're a React developer, it's a safe bet you've encountered fetch waterfalls - also called request waterfalls or network waterfalls. Their distinctive shape crops up in analytics tools when you go try to see what's taking the page you painstakingly designed is taking so long to load.

In this blog post, we’ll go into what fetch waterfalls are, why they happen, how they affect your React applications, and, most importantly, how to avoid them.

What is a Fetch Waterfall?

Let’s start with the basics.

A fetch waterfall is a performance issue that occurs when multiple API calls or fetch requests are chained together and executed one after another. Rather than sending multiple requests in parallel (which would allow them to complete concurrently), the requests are queued and executed in sequence. This results in significant delays in page rendering, especially if the number of fetches increases.

Here's a simple visual representation of what this looks like:

Network tab of dev tools showing fetch waterfall

Source: Sentry.io

From the image above, you can clearly see the sequential delays in a 'waterfall' pattern. Each request starts only after the previous one has finished. In practice, even a slight delay in one request can cause the entire page load time to increase dramatically.

This is particularly troublesome for user experience, as modern web users expect fast-loading applications. A few seconds of delay can lead to higher bounce rates and lower engagement, impacting your application's overall success.

Why Do Fetch Waterfalls Happen?

Fetch waterfalls in React typically occur due to the hierarchical structure of components. Here’s a typical scenario:

  1. Parent Component Fetches Data: The parent component initiates a fetch request when it mounts.
  2. Child Components Await Data: Child components rely on data fetched by the parent and are rendered only once the parent’s data is available.
  3. Sequential Requests: If there are multiple nested components, each one might trigger fetch requests sequentially, causing a "waterfall" effect.

This cascading behavior occurs because components in React render asynchronously. When the parent component fetches data, child components may have to wait until the parent’s request is completed. If these fetches are not handled efficiently, you can end up with a significant delay as each request depends on the previous one.

How to Identify Fetch Waterfalls

To identify if your React application is suffering from fetch waterfalls, you can use tools like Chrome DevTools or React DevTools to monitor network requests and performance. In Chrome DevTools, navigate to the Network tab and look for sequential API calls that are blocking the page’s loading process.

In React DevTools, you can inspect component re-renders and identify any unnecessary dependencies causing fetch requests to be triggered multiple times.

Here are some signs that a fetch waterfall may be occurring:

  • Slow page load times: If your page takes longer than expected to load.
  • Suspicious performance patterns: If you notice a series of API calls that appear to be made one after another instead of in parallel.

How to Prevent Fetch Waterfalls in React

Fortunately, there are several strategies to avoid fetch waterfalls and optimize your React applications for better performance.

1. Fetch Data in Parallel

Instead of waiting for each API request to complete before starting the next one, consider executing multiple fetch requests in parallel. This can be done using JavaScript’s Promise.all() method, which allows you to run multiple promises concurrently.

Here’s an example of fetching data in parallel:

const fetchData = async () => {
const [data1, data2, data3] = await Promise.all([
  fetch('/api/data1').then(res => res.json()),
  fetch('/api/data2').then(res => res.json()),
  fetch('/api/data3').then(res => res.json()),
]);
// Use the data
};
Enter fullscreen mode Exit fullscreen mode

By fetching data in parallel, you reduce the total waiting time and allow the browser to load resources faster.

2. Decouple Component Data Fetching

You can refactor your components so that they don't rely on the parent component’s data to trigger their own fetches. Instead, let each child component handle its own data fetching independently. This can be done by lifting state up and passing down the necessary data or by using libraries like React Query or SWR to manage fetching at the component level.

3. Use React Query or SWR

Libraries like React Query and SWR are great for managing data fetching in React applications. They handle caching, background data fetching, and error handling, while also allowing you to fetch data in parallel efficiently.

React Query, for instance, automatically handles caching, retries, and background syncing for data fetching, ensuring that your components don’t unnecessarily wait for data and that network calls are only made when needed.

import { useQuery } from 'react-query';
const fetchData = async () => {
const res = await fetch('/api/data');
return res.json();
};

const MyComponent = () => {
const { data, isLoading } = useQuery('dataKey', fetchData);

if (isLoading) return <div>Loading...</div>;

return <div>Data: {JSON.stringify(data)}</div>;
};
Enter fullscreen mode Exit fullscreen mode

4. Cache Data to Reduce Redundant Requests

Caching can significantly reduce the need for redundant requests to the server. By storing fetched data locally (in the component state, context, or a caching library like React Query), you can avoid unnecessary network requests, making your application faster and more efficient.

Conclusion

Fetch waterfalls in React can be a major source of performance bottlenecks, but with the right strategies, they can be easily avoided. By fetching data in parallel, decoupling data fetching from components, and leveraging powerful libraries like React Query, you can improve the performance of your React applications and enhance the user experience.

If you're dealing with frequent fetch waterfalls in your React codebase, it's worth taking a step back to analyze your data fetching patterns and implementing these best practices. Ultimately, optimizing how your application interacts with APIs will result in faster, more reliable, and scalable applications.

Top comments (0)