Exploring the Goal's Scope
I'm focused on grasping the project's essence: a React app showcasing Suspense and concurrency for optimized data fetching. Initially, I'm defining the user's intent to inform the design.
Outlining the Application's Structure
Now I'm diving into the application structure. I'm building an API simulation to mimic data fetching, focusing on a "render-as-you-fetch" approach using a manual wrapper to grasp Suspense's mechanics. The goal is to build a demonstrative educational context, so external libraries are not the focus.
Formulating the Implementation Plan
I've sketched out the initial steps for implementation. First, a fake API to simulate network delays. Then, the crux: a wrapPromise function to integrate data fetching with Suspense. This function will manage the promise lifecycle, throwing the promise for Suspense and returning data when ready. Components like UserList and UserDetails will then leverage this to demonstrate the desired features. Next, I'll consider incorporating useTransition for optimized UI responsiveness.
Detailing Component Interactions
I'm now detailing component interactions. The wrapPromise function is critical. My revised thinking involves how read() will function: it throws the promise during the 'pending' state, throws the error in case of any failure, and returns the result once it's available. The UserList and UserDetails components will trigger resource.read(), which either returns data or throws the promise for Suspense to handle. I'll need to consider adding a fallback UI for Suspense and ensure the rendering strategy uses these components. The final refinement will center around integrating useTransition.
Conceptualizing Data Handling
I'm now zeroing in on data handling. To optimize, I'll use separate resources for user and post data, fetching them concurrently. I plan to construct the resources during component initialization, employing wrapPromise to manage the promise lifecycle, making data accessible in read() and handling potential errors. The use of useTransition will also add smoothness to data loading.
Defining the Core Mechanics
I'm now fully immersed in the core mechanics of the solution. I'm focusing on the wrapPromise function, and how read() is going to function to align with the needs of Suspense. My plans center on the user's interaction in tandem with the visual feedback from the application, to make sure the user experience is smooth.
This guide will create a React application demonstrating Suspense for data fetching and Concurrent Rendering features (specifically useTransition).
We will implement the "Render-as-You-Fetch" pattern using a custom resource wrapper. This effectively pauses rendering while data is being fetched without using useEffect.
Prerequisites
Create a new project using Vite (it's faster than CRA):
npm create vite@latest suspense-demo -- --template react
cd suspense-demo
npm install
The Implementation
We will create three files:
api.js: Simulates a slow database.
resource.js: A utility to wrap promises so Suspense can read them.
App.jsx: The UI components using Suspense and useTransition.
1. Create src/api.js
This mocks an API that returns data with an artificial delay.
// src/api.js
// Simulates network delay
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export const fetchUser = async (id) => {
console.log(`Fetching user ${id}...`);
await delay(1500); // Simulate 1.5s latency
return {
id,
name: `User ${id}`,
email: `user${id}@example.com`,
bio: "Loves concurrent rendering and suspense.",
};
};
export const fetchPosts = async (id) => {
console.log(`Fetching posts for user ${id}...`);
await delay(2500); // Simulate 2.5s latency
return [
{ id: 1, title: "React 19 Features" },
{ id: 2, title: "Understanding Suspense" },
{ id: 3, title: "Bye bye useEffect" },
];
};
2. Create src/resource.js
This is the most critical part. To use Suspense for data fetching, a function must throw a Promise if the data isn't ready yet. Most standard fetch calls don't do this, so we need a wrapper.
(Note: In production, libraries like TanStack Query, SWR, or Relay handle this wrapper logic for you.)
// src/resource.js
import { fetchUser, fetchPosts } from "./api";
// Wrapper to integrate Promise with Suspense
function wrapPromise(promise) {
let status = "pending";
let result;
// 1. Listen to the promise
let suspender = promise.then(
(r) => {
status = "success";
result = r;
},
(e) => {
status = "error";
result = e;
}
);
return {
read() {
// 2. If pending, THROW the promise (suspends rendering)
if (status === "pending") {
throw suspender;
}
// 3. If error, THROW the error (caught by ErrorBoundary)
else if (status === "error") {
throw result;
}
// 4. If success, return data
else if (status === "success") {
return result;
}
},
};
}
export function createResource(userId) {
return {
user: wrapPromise(fetchUser(userId)),
posts: wrapPromise(fetchPosts(userId)),
};
}
3. Update src/App.jsx
Here we combine Suspense (to handle loading states) and useTransition (to keep the UI responsive while fetching new data).
// src/App.jsx
import React, { useState, Suspense, useTransition } from "react";
import { createResource } from "./resource";
import "./App.css";
// Initial data fetch
const initialResource = createResource(1);
export default function App() {
const [resource, setResource] = useState(initialResource);
const [currentId, setCurrentId] = useState(1);
// Concurrent Feature: useTransition
// isPending becomes true while the next state update is computing/suspending
const [isPending, startTransition] = useTransition();
const handleNextUser = () => {
const nextId = currentId + 1;
setCurrentId(nextId);
// TRANSITION: This tells React to fetch the new data in the background.
// The UI will NOT immediately switch to the fallback spinner.
// It will keep the old data visible until the new data is ready.
startTransition(() => {
setResource(createResource(nextId));
});
};
return (
<div className="container">
<h1>Suspense & Concurrent Demo</h1>
<button
onClick={handleNextUser}
disabled={isPending}
className="btn"
>
{isPending ? "Loading Next..." : "Load Next User"}
</button>
{/* Visual indicator that a transition is happening in background */}
<div style={{ opacity: isPending ? 0.5 : 1, transition: 'opacity 0.2s' }}>
{/* Suspense Boundary for Profile */}
<Suspense fallback={<div className="loading">Loading Profile...</div>}>
<UserProfile resource={resource} />
{/* Nested Suspense: Posts can load independently after Profile */}
<Suspense fallback={<div className="loading-small">Loading Posts...</div>}>
<UserPosts resource={resource} />
</Suspense>
</Suspense>
</div>
</div>
);
}
// Note: These components do not use useEffect!
// They just try to read data. If it's missing, they suspend.
function UserProfile({ resource }) {
const user = resource.user.read(); // Pauses here if data not ready
return (
<div className="card">
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Bio: {user.bio}</p>
</div>
);
}
function UserPosts({ resource }) {
const posts = resource.posts.read(); // Pauses here if data not ready
return (
<div className="card">
<h3>Recent Posts</h3>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
4. Add basic CSS (Optional)
Add this to src/App.css to make it readable.
.container { max-width: 600px; margin: 0 auto; text-align: center; font-family: sans-serif; padding: 20px; }
.card { background: #f4f4f4; padding: 20px; border-radius: 8px; margin: 20px 0; text-align: left; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.btn { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
.btn:disabled { background: #ccc; cursor: not-allowed; }
.loading { font-size: 1.5rem; color: #666; margin: 40px 0; }
.loading-small { color: #888; font-style: italic; margin: 10px 0; }
How to Run
npm run dev
Usage & Explanation
-
Initial Load:
- When you refresh the page, you will see "Loading Profile..." immediately.
- This is because
initialResource is passed, the data isn't ready, so UserProfile "throws" a promise, and the <Suspense> boundary catches it to show the fallback.
-
Click "Load Next User":
- Once the button is clicked,
startTransition triggers.
- React attempts to render User 2.
- User 2's data is missing, so it attempts to suspend.
- The Optimization: Because we used
startTransition, React does not remove User 1's data yet. Instead, the UI stays on User 1, and the opacity dims (controlled by isPending).
- Once User 2's data arrives in the background, React updates the DOM to show User 2.
-
Nested Suspense:
- The
UserProfile will load after 1.5s.
- The
UserPosts will load after 2.5s.
- Because
UserPosts is wrapped in its own inner <Suspense>, the Profile will appear first, while the Posts area continues to show its own specific loader ("Loading Posts..."). This is called Selective Hydration/Streaming.
Key Benefits Demonstrated
- No
useEffect: No complex dependency arrays or if (loading) return <Spinner /> inside every component.
- Race Condition Handling: Because we create the resource before setting state, we avoid common bugs where previous requests resolve after current ones.
- Better UX (Concurrent Features): The user continues to see the old meaningful content while the new content loads, rather than a jarring flash of a white screen or loading spinner.