DEV Community

Cover image for React, deeply · 4. Data fetching: Suspense, transitions and cache boundaries
Amit chakraborty
Amit chakraborty

Posted on Originally published at amitchakraborty.dev

React, deeply · 4. Data fetching: Suspense, transitions and cache boundaries

React, deeply · Chapter 4 of 12 · Web · new chapter every Monday night

By the end of this chapter: Fetch data without the loading-flash and waterfall problems.

The problem

Marcus is a senior engineer at a fintech startup. He is responsible for the "Portfolio Overview" dashboard, a complex screen that aggregates data from four different microservices: user profile, asset balances, historical performance, and real-time market alerts.

When the dashboard was first built, the team used the standard useEffect pattern: each component fetched its own data on mount. In local development, it looked fine. In production, users on 4G connections see a "popcorn UI." First, the header appears. Then, 200ms later, the sidebar flashes. 500ms after that, the balance card appears, pushing the performance graph down the page. Finally, the market alerts pop in, causing the entire layout to shift again.

The metric that moved was the Cumulative Layout Shift (CLS), which spiked to 0.45 (well into the "poor" category). More importantly, the Time to Interactive (TTI) was delayed because the browser was stuck in a "waterfall": Component A had to render to trigger the fetch for Component B, which had to render to trigger Component C. This cost the team a 15% drop in mobile engagement, as users perceived the app as "broken" or "slow" before they could even click a button.

Before you start

To follow this chapter, you need a React 18 or 19 environment. We will use a mock API to simulate network latency reliably.

  1. Ensure you have Node.js 18+ installed.
  2. Create a new project: npm create vite@latest suspense-demo -- --template react
  3. Install the only external dependency we will use for cache management: npm install @tanstack/react-query@5.59.0
  4. Verify your setup by running npm run dev. If the Vite splash screen appears, you are ready.

Why does the "loading spinner" pattern fail?

In Chapter 1, we looked at how React reconciles changes. When you use the useEffect fetch pattern, you are essentially telling React: "Render what you can now, and I'll give you more data later."

The problem is that React cannot "see" into your useEffect. To React, the component is finished rendering as soon as it returns a loading spinner. Only after the browser paints that spinner does the effect run, the fetch start, and—eventually—a state update trigger a second render cycle.

This creates three production failures:

  1. The Waterfall: If <Parent> fetches data and only then renders <Child>, and <Child> then fetches its own data, the user waits for Latency A + Latency B.
  2. The Loading Flash: If a fetch takes 50ms, the user sees a spinner flicker for one frame. This is more jarring than seeing nothing at all.
  3. Race Conditions: If a user clicks "User A" then quickly clicks "User B", the response for "User A" might arrive after "User B", overwriting the state with the wrong data.

Suspense changes the contract. Instead of rendering a "hole" (the spinner) and filling it later, a component "suspends." It tells React: "I am not ready to render yet; here is a Promise. Wake me up when it settles."

How do Transitions prevent the "loading flash"?

The biggest mistake engineers make with Suspense is thinking it is just a new way to show spinners. The real power of Suspense lies in useTransition.

When you trigger a state change inside startTransition, React does something counter-intuitive: it keeps the old UI on screen while it renders the new UI in the background. If the new UI hits a Suspense boundary (because it needs data), React waits.

It does not show the fallback spinner immediately. It stays on the current screen, keeping it interactive, until either the data is ready or a timeout is reached. This is the difference between a "cheap" feeling app that flickers and a "pro" app that feels like a native OS.

Where does the cache live?

Suspense is not a data-fetching library; it is a communication mechanism. It requires a cache that lives outside the component tree.

When a component renders, it asks the cache for data.

  • If the data is there: The component renders immediately.
  • If the data is missing: The cache initiates a fetch and throws the Promise.
  • If the fetch is in progress: The cache throws the existing Promise.

This "throwing a promise" is the part most developers find embarrassing because it breaks standard JavaScript expectations. But it allows React to catch the promise at the Suspense boundary and manage the scheduling of the render.

Build it

We will build a profile viewer that switches between users without showing a loading spinner for every click, and without layout shift.

1. Set up the Mock API and Query Client

Create a file src/api.js. We use a manual delay to simulate a slow 3G connection.

// src/api.js
export const fetchUserData = async (id) => {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return {
    id,
    name: id === 1 ? "Marcus" : "Emma",
    joined: "2023-10-01",
  };
};
Enter fullscreen mode Exit fullscreen mode

Update src/main.jsx to provide the Query Client. We must set suspense: true (in v5, this is done via the useSuspenseQuery hook).

// src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

2. Create the Suspenseful Component

Create src/UserProfile.jsx. This component does not handle its own loading state.

// src/UserProfile.jsx
import { useSuspenseQuery } from '@tanstack/react-query';
import { fetchUserData } from './api';

export function UserProfile({ userId }) {
  // This hook throws a promise if data is missing.
  // The component logic stops here until the promise resolves.
  const { data } = useSuspenseQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUserData(userId),
  });

  return (
    <div style={{ border: '1px solid #ccc', padding: '1rem', marginTop: '1rem' }}>
      <h2>{data.name}</h2>
      <p>Member since: {data.joined}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

3. Implement the Transition logic

In src/App.jsx, we will use useTransition to switch users.

// src/App.jsx
import { useState, useTransition, Suspense } from 'react';
import { UserProfile } from './UserProfile';

export default function App() {
  const [userId, setUserId] = useState(1);
  const [isPending, startTransition] = useTransition();

  const handleUserChange = (newId) => {
    // startTransition tells React: "Don't show the Suspense fallback yet."
    // Keep the current UI responsive while the next user's data loads.
    startTransition(() => {
      setUserId(newId);
    });
  };

  return (
    <main style={{ padding: '2rem', opacity: isPending ? 0.6 : 1 }}>
      <h1>Dashboard</h1>
      <button onClick={() => handleUserChange(1)} disabled={userId === 1}>
        User 1
      </button>
      <button onClick={() => handleUserChange(2)} disabled={userId === 2}>
        User 2
      </button>

      {isPending && <span> Loading next profile...</span>}

      <Suspense fallback={<p>Loading initial profile...</p>}>
        <UserProfile userId={userId} />
      </Suspense>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

How to confirm it worked:

  1. Refresh the page. You should see "Loading initial profile..." for 1 second. This is the initial Suspense fallback.
  2. Click "User 2".
  3. The Result: The "User 1" profile stays on screen. The UI does not disappear. The "Loading next profile..." text appears (because of isPending), and the opacity drops.
  4. After 1 second, the UI updates instantly to "User 2".
  5. There was no layout shift and no "popcorn" effect.

When this breaks

1. The "Infinite Loop" fetch

Symptom: The network tab shows hundreds of requests per second, and the browser tab eventually crashes.
Cause: You are calling a fetch function inside the render body that is not wrapped in a cache (like TanStack Query or React's cache function in Next.js).
Fix: Ensure your data fetching logic is stable. The function passed to useSuspenseQuery must not create a new promise on every render unless the queryKey changes.

2. The "Nested Waterfall"

Symptom: You have three Suspense boundaries, and they still load one after another.
Cause: You placed a <Suspense> boundary around every single component.
Fix: Move the Suspense boundary higher. One boundary around a group of components allows React to coordinate them. If you want them to load in parallel, they must be siblings under the same boundary, and their data fetching must start as soon as they begin rendering.

3. "Transition ignored"

Symptom: You wrapped setUserId in startTransition, but the UI still jumped to the loading spinner.
Cause: You likely have a useEffect inside UserProfile that is triggering a secondary state update, or you are using a library that doesn't fully support React 18's concurrent features.
Fix: Remove useEffect for data fetching. Use useSuspenseQuery or the use hook (in React 19).

What it costs

Complexity of State: You can no longer rely on if (loading) return <Spinner /> inside your component. This logic is moved to the parent or the boundary. This makes components cleaner but the architecture harder to trace for juniors.

Memory Overhead: Caching data "outside" the tree means you must manage cache invalidation. If you never clear the cache, your app's memory usage will grow linearly with every "page" the user visits.

Server-Side Rendering (SSR) Requirements: Suspense requires a streaming-capable server (like Node.js or Edge functions) to be truly effective. If you are using a static "Single Page App" (SPA) on a basic CDN, you still get the UX benefits, but you don't get the SEO/First Contentful Paint benefits of streaming.

In the interview

The Question: "How do you handle data fetching in a large-scale React app to avoid waterfalls?"

A Weak Answer: "I use useEffect and show a loading spinner. If it's slow, I use Promise.all in the parent." This is weak because it doesn't address layout shift or the fact that Promise.all requires the parent to know exactly what every child needs, breaking encapsulation.

A Strong Answer: "I use Suspense boundaries combined with Concurrent Transitions. This allows the UI to stay interactive on the current state while the next state is prepared in memory. I use a cache-integrated fetcher (like TanStack Query) to ensure that multiple components requesting the same data don't trigger redundant network calls. For performance, I lift the fetch as high as possible—or use prefetching in event handlers—to ensure the network request starts the moment the user intends to navigate, not after the component mounts."

The Senior/Staff Follow-up: "How do you handle a scenario where one data source is fast (50ms) and another is slow (2s) on the same screen?"
A senior engineer will discuss Selective Hydration or Nested Suspense Boundaries. They might suggest wrapping the "slow" component in its own <Suspense> boundary so the rest of the page can become interactive immediately, while the slow part shows a skeleton state. This is a trade-off between "loading everything at once" and "getting the user to the first interaction as fast as possible."

Your tasks

  1. The "Slow Component" trap: Add a second component, MarketAlerts, that takes 3 seconds to load. Place it inside the same <Suspense> boundary as UserProfile. Observe how the entire profile is now delayed by 3 seconds.
  2. The "Independent Boundary" fix: Move MarketAlerts into its own <Suspense> boundary with its own fallback. Confirm that the UserProfile now appears after 1 second, while the alerts continue to load.
  3. The "Prefetch" challenge: Add an onMouseEnter handler to the buttons in App.jsx. Use the queryClient.prefetchQuery method to start fetching the user data when the user hovers over the button. Use the Network tab to prove the fetch starts before the click.
  4. The "Broken Cache" simulation: Create a component that fetches data using a raw fetch inside the render body (throwing the promise manually) but without a cache. Observe the infinite loop in the Network tab and explain why it happens.

Your tasks this week

Do the exercises above before the next chapter. Reading a tutorial and doing
one are different activities and only one of them changes what you can build.

Stuck on any of them? Say so — describe what you tried and what happened:
tell me where you got stuck. I read every one, and the questions
that come back more than twice get answered in the next chapter.

React, deeply

Chapter 4 of 12. New chapter every Monday night.
Next: Server Components and where your code runs.

· The full syllabus and every chapter so far
· Subscribers also get the condensed notes for this chapter, the running
recap of everything the series has covered, and the extended guidance:
subscribe


Written by Amit Chakraborty — founding engineer and senior architect: React Native, AI and RAG systems, production architecture. Portfolio · LinkedIn · GitHub.

Need this built, reviewed or taught to your team? Get in touch or email amit@devamit.co.in. Available for senior and founding engineering roles, consulting and training, remote worldwide.

Top comments (0)