• React

Fetch Waterfall in React

by Lazar Nikolov

added on October 21, 2024 (1mo ago)

Have you seen this problem?

Or maybe this one?

You’ve most likely seen this:

export const Component = () => {
  const [data, setData] = useState();
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch(api);
      const json = await res.json();
      setData(json);
      setLoading(false);
    };
 
    fetchData();
  }, []);
 
  if (loading) {
    return <Spinner />;
  }
 
  return (
    <>
      {' '}
      ... <AnotherComponent /> ...{' '}
    </>
  );
};

Hint: they’re all the same. The first image is Sentry’s Event Details page, the second is Chrome’s Network tab, and the code snippet is what causes it.


If you can answer yes to any of these, then you need to keep reading. If not, you still need to keep reading, so your future self can thank you.

This is called “fetch waterfall” and it’s a common data fetching issue in React. It happens when you create a hierarchy of components that fetch their own data and show a “Loading” state before rendering their child component, which then does the same etc.