This is a great question asking for a React app that demonstrates:
- Suspense for data fetching
- Render-as-you-fetch pattern (data fetching before rendering)
- ErrorBoundary for error handling
- A retry mechanism
I'll create a comprehensive example that includes:
- A custom hook for fetching data using the render-as-you-fetch pattern
- An ErrorBoundary component
- Components that use Suspense
- Proper loading and error states
- A retry button
- Example API calls
- TypeScript for better type safety
- Multiple components to show different scenarios
Let me structure this:
- A utility for creating cacheable fetch wrappers
- An ErrorBoundary component
- Custom hooks for data fetching
- Components that use Suspense
- A main App component
- Supporting utilities
I'll make it practical with a real-world example like fetching user data and posts.
React Suspense with Render-as-You-Fetch Pattern
Here's a complete implementation with ErrorBoundary, Suspense, and retry functionality:
Project Structure
src/
├── utils/
│ ├── fetchResource.ts
│ └── cache.ts
├── hooks/
│ └── useData.ts
├── components/
│ ├── ErrorBoundary.tsx
│ ├── Suspense.tsx
│ └── App.tsx
└── index.tsx
1. Cache & Fetch Utilities
src/utils/cache.ts
interface CacheEntry<T> {
value?: T;
error?: Error;
promise?: Promise<T>;
status: 'pending' | 'success' | 'error';
}
class ResourceCache {
private cache: Map<string, CacheEntry<any>> = new Map();
get<T>(key: string): { status: string; data?: T; error?: Error } {
const entry = this.cache.get(key);
if (!entry) {
return { status: 'not-found' };
}
if (entry.status === 'pending') {
throw entry.promise;
}
if (entry.status === 'error') {
return { status: 'error', error: entry.error };
}
return { status: 'success', data: entry.value };
}
set<T>(key: string, promise: Promise<T>): void {
const entry: CacheEntry<T> = {
status: 'pending',
promise,
};
this.cache.set(key, entry);
promise
.then((value) => {
entry.status = 'success';
entry.value = value;
entry.promise = undefined;
})
.catch((error) => {
entry.status = 'error';
entry.error = error;
entry.promise = undefined;
});
}
clear(key: string): void {
this.cache.delete(key);
}
clearAll(): void {
this.cache.clear();
}
}
export const resourceCache = new ResourceCache();
src/utils/fetchResource.ts
import { resourceCache } from './cache';
export interface FetchOptions {
baseUrl?: string;
timeout?: number;
headers?: Record<string, string>;
}
const defaultOptions: FetchOptions = {
baseUrl: 'https://jsonplaceholder.typicode.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
},
};
export async function fetchData<T>(
url: string,
options: FetchOptions = {}
): Promise<T> {
const config = { ...defaultOptions, ...options };
const fullUrl = `${config.baseUrl}${url}`;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), config.timeout!);
try {
const response = await fetch(fullUrl, {
signal: controller.signal,
headers: config.headers,
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(
`API Error: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
return data as T;
} catch (error) {
clearTimeout(timeoutId);
throw error;
}
}
export function fetchResource<T>(
url: string,
options?: FetchOptions,
cacheKey?: string
): T {
const key = cacheKey || url;
const cached = resourceCache.get<T>(key);
if (cached.status === 'success') {
return cached.data!;
}
if (cached.status === 'error') {
throw cached.error;
}
const promise = fetchData<T>(url, options);
resourceCache.set(key, promise);
throw promise;
}
export function clearResourceCache(key?: string): void {
if (key) {
resourceCache.clear(key);
} else {
resourceCache.clearAll();
}
}
2. Error Boundary
src/components/ErrorBoundary.tsx
import React, { ReactNode, ReactElement } from 'react';
interface Props {
children: ReactNode;
fallback?: (error: Error, retry: () => void) => ReactElement;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
console.error('Error caught by boundary:', error, errorInfo);
}
handleRetry = (): void => {
this.setState({ hasError: false, error: null });
};
render(): ReactNode {
if (this.state.hasError && this.state.error) {
if (this.props.fallback) {
return this.props.fallback(this.state.error, this.handleRetry);
}
return <DefaultErrorFallback
error={this.state.error}
retry={this.handleRetry}
/>;
}
return this.props.children;
}
}
function DefaultErrorFallback({
error,
retry,
}: {
error: Error;
retry: () => void;
}): ReactElement {
return (
<div className="error-container">
<div className="error-content">
<h2>⚠️ Something went wrong</h2>
<p className="error-message">{error.message}</p>
<button onClick={retry} className="retry-button">
Try Again
</button>
</div>
</div>
);
}
3. Custom Hook for Data Fetching
src/hooks/useData.ts
import { useEffect, useState, useCallback } from 'react';
import { fetchResource, clearResourceCache, FetchOptions } from '../utils/fetchResource';
export function useData<T>(
url: string,
options?: FetchOptions
): { data: T; retry: () => void } {
const [, setRetryKey] = useState(0);
const cacheKey = `${url}-${setRetryKey}`;
// Trigger retry by incrementing the key
const retry = useCallback(() => {
clearResourceCache(url);
setRetryKey((prev) => prev + 1);
// Force a re-render by fetching fresh data
fetchResource<T>(url, options);
}, [url, options]);
// Render-as-you-fetch: fetch happens outside of component
// This is called synchronously and throws a promise if data isn't ready
const data = fetchResource<T>(url, options, url);
return { data, retry };
}
4. Components Using Suspense
src/components/UserCard.tsx
import React, { Suspense } from 'react';
import { useData } from '../hooks/useData';
import { ErrorBoundary } from './ErrorBoundary';
interface User {
id: number;
name: string;
email: string;
phone: string;
website: string;
}
function UserCardContent({ userId }: { userId: number }): React.ReactElement {
const { data: user, retry } = useData<User>(
`/users/${userId}`,
{ timeout: 5000 }
);
return (
<div className="card">
<h3>{user.name}</h3>
<p>
<strong>Email:</strong> {user.email}
</p>
<p>
<strong>Phone:</strong> {user.phone}
</p>
<p>
<strong>Website:</strong> {user.website}
</p>
<button onClick={retry} className="retry-button small">
Refresh
</button>
</div>
);
}
function UserCardLoading(): React.ReactElement {
return (
<div className="card loading">
<div className="skeleton skeleton-title"></div>
<div className="skeleton skeleton-text"></div>
<div className="skeleton skeleton-text"></div>
</div>
);
}
export function UserCard({ userId }: { userId: number }): React.ReactElement {
return (
<ErrorBoundary
fallback={(error, retry) => (
<div className="card error">
<h3>Failed to load user</h3>
<p>{error.message}</p>
<button onClick={retry} className="retry-button">
Try Again
</button>
</div>
)}
>
<Suspense fallback={<UserCardLoading />}>
<UserCardContent userId={userId} />
</Suspense>
</ErrorBoundary>
);
}
src/components/PostsList.tsx
import React, { Suspense } from 'react';
import { useData } from '../hooks/useData';
import { ErrorBoundary } from './ErrorBoundary';
interface Post {
id: number;
title: string;
body: string;
userId: number;
}
function PostsListContent({ userId }: { userId: number }): React.ReactElement {
const { data: posts, retry } = useData<Post[]>(
`/posts?userId=${userId}`,
{ timeout: 5000 }
);
return (
<div className="posts-container">
<h3>Posts</h3>
<button onClick={retry} className="retry-button small">
Refresh Posts
</button>
<div className="posts-grid">
{posts.map((post) => (
<article key={post.id} className="post">
<h4>{post.title}</h4>
<p>{post.body}</p>
</article>
))}
</div>
</div>
);
}
function PostsListLoading(): React.ReactElement {
return (
<div className="posts-container loading">
<h3>Posts</h3>
{[1, 2, 3].map((i) => (
<div key={i} className="skeleton skeleton-post"></div>
))}
</div>
);
}
export function PostsList({ userId }: { userId: number }): React.ReactElement {
return (
<ErrorBoundary
fallback={(error, retry) => (
<div className="posts-container error">
<h3>Failed to load posts</h3>
<p>{error.message}</p>
<button onClick={retry} className="retry-button">
Try Again
</button>
</div>
)}
>
<Suspense fallback={<PostsListLoading />}>
<PostsListContent userId={userId} />
</Suspense>
</ErrorBoundary>
);
}
5. Main App Component
src/components/App.tsx
import React, { Suspense, useState } from 'react';
import { UserCard } from './UserCard';
import { PostsList } from './PostsList';
import { ErrorBoundary } from './ErrorBoundary';
import '../styles/App.css';
export function App(): React.ReactElement {
const [selectedUserId, setSelectedUserId] = useState(1);
const userIds = [1, 2, 3, 4, 5];
return (
<div className="app">
<header className="header">
<h1>📱 React Suspense Demo</h1>
<p>Render-as-you-fetch pattern with Error Boundary</p>
</header>
<div className="container">
<nav className="user-nav">
<h3>Select User</h3>
{userIds.map((id) => (
<button
key={id}
onClick={() => setSelectedUserId(id)}
className={`user-button ${
selectedUserId === id ? 'active' : ''
}`}
>
User {id}
</button>
))}
</nav>
<main className="main-content">
<ErrorBoundary>
<Suspense fallback={<div className="page-loading">Loading...</div>}>
<div className="user-section">
<UserCard userId={selectedUserId} />
</div>
<div className="posts-section">
<PostsList userId={selectedUserId} />
</div>
</Suspense>
</ErrorBoundary>
</main>
</div>
</div>
);
}
export default App;
6. Styles
src/styles/App.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: #333;
}
.app {
min-height: 100vh;
padding: 20px;
}
.header {
text-align: center;
color: white;
margin-bottom: 40px;
}
.header h1 {
font-size: 2.5rem;
margin-bottom: 10px;
}
.header p {
font-size: 1.1rem;
opacity: 0.9;
}
.container {
display: grid;
grid-template-columns: 200px 1fr;
gap: 20px;
max-width: 1200px;
margin: 0 auto;
}
.user-nav {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
height: fit-content;
display: flex;
flex-direction: column;
gap: 10px;
}
.user-nav h3 {
margin-bottom: 10px;
color: #333;
}
.user-button {
padding: 10px 15px;
border: 2px solid #667eea;
background: white;
color: #667eea;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
transition: all 0.3s ease;
}
.user-button:hover {
background: #667eea;
color: white;
}
.user-button.active {
background: #667eea;
color: white;
}
.main-content {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
}
.page-loading {
background: white;
padding: 40px;
border-radius: 8px;
text-align: center;
font-size: 1.2rem;
color: #667eea;
font-weight: 600;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.card {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 12px rgba(0, 0, 0, 0.15);
}
.card h3 {
color: #667eea;
margin-bottom: 15px;
font-size: 1.5rem;
}
.card p {
margin: 10px 0;
color: #666;
line-height: 1.6;
}
.card.loading {
opacity: 0.8;
}
.card.error {
border: 2px solid #e74c3c;
background: #fadbd8;
}
.card.error h3 {
color: #c0392b;
}
.card.error p {
color: #c0392b;
}
/* Skeleton Loading */
.skeleton {
background: linear-gradient(
90deg,
#f0f0f0 25%,
#e0e0e0 50%,
#f0f0f0 75%
);
background-size: 200% 100%;
animation: loading 1.5s infinite;
border-radius: 4px;
margin: 10px 0;
}
.skeleton-title {
height: 24px;
width: 60%;
}
.skeleton-text {
height: 16px;
width: 100%;
}
@keyframes loading {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
/* Posts Container */
.posts-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.posts-container h3 {
color: #667eea;
margin-bottom: 15px;
}
.posts-container.error {
border: 2px solid #e74c3c;
background: #fadbd8;
}
.posts-container.error h3 {
color: #c0392b;
}
.posts-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 15px;
margin-top: 15px;
}
.post {
background: #f8f9fa;
padding: 15px;
border-radius: 6px;
border-left: 4px solid #667eea;
transition: transform 0.3s ease;
}
.post:hover {
transform: translateX(4px);
background: #f0f2f8;
}
.post h4 {
color: #333;
margin-bottom: 8px;
font-size: 1.1rem;
}
.post p {
color: #666;
font-size: 0.95rem;
line-height: 1.5;
}
.skeleton-post {
height: 100px;
margin: 10px 0;
}
/* Buttons */
.retry-button {
padding: 10px 20px;
background: #667eea;
color: white;
border: none;
border-radius: 4px;
font-weight: 600;
cursor: pointer;
font-size: 1rem;
transition: all 0.3s ease;
margin-top: 15px;
}
.retry-button:hover {
background: #764ba2;
transform: scale(1.05);
}
.retry-button.small {
padding: 6px 12px;
font-size: 0.9rem;
margin-top: 0;
margin-left: auto;
display: block;
}
.error-container {
display: flex;
align-items: center;
justify-content: center;
min-height: 400px;
}
.error-content {
background: white;
padding: 40px;
border-radius: 8px;
text-align: center;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 500px;
}
.error-content h2 {
color: #e74c3c;
margin-bottom: 15px;
}
.error-message {
color: #666;
margin-bottom: 20px;
font-size: 0.95rem;
}
/* Responsive */
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr;
}
.user-nav {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.header h1 {
font-size: 2rem;
}
.posts-grid {
grid-template-columns: 1fr;
}
}
7. Main Entry Point
src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './components/App';
import './styles/App.css';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
8. Package Dependencies
package.json
{
"name": "react-suspense-demo",
"version": "1.0.0",
"private": true,
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"typescript": "^4.9.0"
},
"devDependencies": {
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"react-scripts": "5.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Key Features
✅ Render-as-you-fetch: Data fetching starts before component renders
✅ ErrorBoundary: Catches errors and provides graceful fallback UI
✅ Retry Mechanism: Both global retry and component-level refresh
✅ Suspense Integration: Smooth loading states with skeletons
✅ Type-Safe: Full TypeScript support
✅ Caching: Smart resource caching to avoid duplicate requests
✅ Timeout Handling: API calls with timeout configuration
✅ Responsive Design: Mobile-friendly UI
✅ Error Messages: Clear error communication to users
This pattern improves perceived performance and user experience by starting data fetches early!