I’m planning to create a concise example: a single-page app using React 18, focusing on its concurrency features. I’ll implement automatic batching, transitions with startTransition/useTransition, and useDeferredValue. We can also utilize Suspense for code splitting and data fetching. The idea is to build a simple app that fetches user details from JSONPlaceholder, leveraging a resource wrapper for promises. I'll also consider using SuspenseList to control the order of the UI reveals.Setting up the React app
Here are some setup steps for our project. I can use npm create vite@latest suspense-concurrent-demo -- --template react or npx create-react-app, but I’ll opt for Vite since it's more modern. Many are familiar with Create React App too, so it’s worth mentioning.
Next, I'll implement the data fetching layer with createResource(fetchFn) for caching and use it within Suspense boundaries in App.jsx. The App will manage the selected userId state, create a resource for the initial user list, and wrap UsersList in <Suspense>. I'll ensure it's efficient by keeping the resource outside of rerenders.Implementing concurrency in the app
To achieve concurrency, I’ll use useTransition, which helps avoid blocking the main UI. I need to ensure that resources are hooked to changing IDs, creating a resource for each specific ID.
At the App level, I’ll manage the state for userId and use useTransition to update resources without blocking. We’ll also need a usersListResource, which can be created once outside the component for efficiency. In the main file, we’ll utilize ReactDOM.createRoot(root).render(...).
The file structure will include main.jsx (or index.jsx), App.jsx, api.js, and components like UsersList.jsx, UserDetails.jsx, and maybe LoadingIndicator.jsx for displaying a loading state.Setting up detailed code structure
In main.jsx, I’ll import React and ReactDOM, and render the App component using ReactDOM.createRoot. I’ll ensure it runs in strict mode for better error handling.
In api.js, I’ll implement a caching mechanism using a Map to store the resources. The wrapPromise function handles promise states for pending, success, and error. The fetchJson function will fetch data, handle any network errors, and introduce an optional delay for simulating loading.
I need to be cautious while creating resources, as fetchJson efficiently caches them to return the same resource for identical URLs.Crafting the app structure and details
In App.jsx, I'll use useTransition to manage user selection without blocking the UI. While getUserResource(id).read() could potentially construct new resources on each render, caching ensures subsequent calls return the already fetched data. When users are selected, React will keep displaying the previous UI until the new UserDetails are loaded, thanks to the concurrency features in React 18.
I’ll also introduce a prefetchUser function to fetch neighboring user data upon hover, which helps enhance performance by filling the cache in advance. Finally, I want to consider error boundaries, and I'll provide a small ErrorBoundary class for handling errors gracefully.
For clarity, I will outline the necessary steps to set up the Vite app, install the required packages, and replace the existing files. This will ensure a seamless and understandable process for the user. Below is a minimal React 18 app that uses Suspense and concurrent rendering features (useTransition) to optimize data fetching.
It:
Uses Suspense boundaries to show fallbacks while data is loading.
Uses a simple cache + “resource” wrapper to integrate data fetching with Suspense.
Uses useTransition so “slow” data loading doesn’t block the UI.
(If you prefer CRA, you can adapt the file structure accordingly.)
2. Enable concurrent rendering (React 18)
main.jsx (or main.tsx if using TS):
jsx
// src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
createRoot enables React 18 concurrent features.
3. Suspense-aware data layer with caching
Create an api.js file that:
Wraps fetch promises in an object with .read() that throws while pending (the Suspense pattern).
Caches results by URL to avoid duplicate requests and to reuse data across renders.
js
// src/api.js
// Simple in-memory cache keyed by URL
const cache = new Map();
// Wrap a promise so that .read() either:
// - returns the data
// - throws the promise (to trigger Suspense)
// - throws the error
function wrapPromise(promise) {
let status = 'pending';
let result;
const suspender = promise.then(
(value) => {
status = 'success';
result = value;
},
(error) => {
status = 'error';
result = error;
}
);
return {
read() {
if (status === 'pending') {
throw suspender; // Suspense will catch this
} else if (status === 'error') {
throw result; // Let an ErrorBoundary catch this
} else if (status === 'success') {
return result;
}
},
};
}
function fetchJsonWithDelay(url, delayMs = 800) {
if (cache.has(url)) {
return cache.get(url);
}
const promise = fetch(url)
.then((res) => {
if (!res.ok) {
throw new Error(`Request failed: ${res.status}`);
}
return res.json();
})
// artificial delay so Suspense behavior is visible
.then(
(data) =>
new Promise((resolve) => setTimeout(() => resolve(data), delayMs))
);
const resource = wrapPromise(promise);
cache.set(url, resource);
return resource;
}
// Public API
export function getUsersResource() {
return fetchJsonWithDelay('https://jsonplaceholder.typicode.com/users');
}
export function getUserResource(id) {
return fetchJsonWithDelay(
`https://jsonplaceholder.typicode.com/users/${id}`
);
}
// Optional: prefetch for optimization (e.g., on hover)
export function prefetchUser(id) {
getUserResource(id);
}
4. App with Suspense + useTransition
App.jsx:
A Suspense boundary around the user list.
Another Suspense boundary around user details.
useTransition so switching users doesn’t immediately blank out the details; React keeps old details visible while new data loads, and we show a small “pending” indicator.
jsx
5. Optional: Error boundary (recommended around Suspense)
If you want to handle errors (e.g., network failures), wrap Suspense with an error boundary: