manual-retry.tsx
Overview
manual-retry.tsx is a React component file demonstrating an integration pattern for manual retry of asynchronous data fetching within a Suspense-enabled React application. It leverages:
React’s Suspense for declarative data fetching with fallback loading states.
Error boundaries to catch and display errors that occur during data fetching.
A manual retry UI that allows users to explicitly trigger a retry of the failed data fetch.
Custom hooks (
useRemoteData) and preloading (preloadRemote) utilities to manage remote data fetching lifecycle.
This file primarily serves as a minimal example showing how to combine these mechanisms to create robust, user-friendly retry flows in React applications dealing with asynchronous data.
File Structure & Components
1. Demo Component
const Demo = () => {
const { data } = useRemoteData()
return <div>data: {data}</div>
}
Purpose:
Fetches and displays remote data using the custom hookuseRemoteDatawhich internally uses SWR or a similar data fetching mechanism with Suspense enabled.Functionality:
Calls
useRemoteData()to retrieve{ data }.Renders the fetched
datainside a<div>.
Usage:
Rendered inside Suspense and Error Boundary components to handle loading and error states respectively.
2. Fallback Component
function Fallback({ resetErrorBoundary }: any) {
return (
<div role="alert">
<p>Something went wrong</p>
<button onClick={() => resetErrorBoundary()}>
retry
</button>
</div>
)
}
Purpose:
Serves as the fallback UI displayed by theErrorBoundarywhen the data fetching throws an error.Props:
resetErrorBoundary: a function provided by the error boundary to reset its error state and attempt a retry.
Features:
Shows an error message.
Includes a retry button which, when clicked, calls
resetErrorBoundaryto clear the error and re-initiate rendering and data fetching.
Usage Example:
Passed as theFallbackComponentprop toErrorBoundary.
3. RemoteData Component (Default Export)
function RemoteData() {
return (
<div className="App">
<ErrorBoundary
FallbackComponent={Fallback}
onReset={() => {
preloadRemote()
}}
>
<Suspense fallback={<div>loading</div>}>
<Demo />
</Suspense>
</ErrorBoundary>
</div>
)
}
Purpose:
The main component orchestrating the rendering of remote data with robust error handling and retry capabilities.Key Elements:
ErrorBoundary:
Wraps theDemocomponent to catch errors during rendering (such as thrown promises or exceptions in Suspense-enabled data fetching).FallbackComponent: set toFallback, which shows error UI and retry button.onReset: callback invoked when the error boundary is reset. CallspreloadRemote()to preload data before retrying.
Suspense:
Suspends rendering ofDemountil the data is ready.Provides a fallback UI (
<div>loading</div>) while data is being fetched.
Workflow:
When the component mounts,
DemousesuseRemoteDatato fetch data.If fetching succeeds, data is displayed.
If fetching fails (throws an error),
ErrorBoundarycatches it and displaysFallback.Clicking "retry" in
Fallbackresets the error boundary and triggersonReset, which preloads remote data before re-renderingDemo.
Export:
This component is the default export of the file and typically used within the application to show the remote data with retry support.
Important Implementation Details & Algorithms
Suspense-based Data Fetching:
The file assumesuseRemoteDatauses Suspense internally. Suspense suspends rendering until data is ready or an error is thrown, enabling declarative asynchronous data fetching.Error Boundary Handling:
TheErrorBoundarycomponent fromreact-error-boundarylibrary catches errors thrown during render (including Suspense suspensions that result in errors). It renders theFallbackUI instead of crashing the entire React tree.Manual Retry Flow:
User clicks the retry button in the
Fallbackcomponent.The
resetErrorBoundary()call clears the error state.onReseton theErrorBoundarytriggerspreloadRemote(), which preloads the data before theDemocomponent re-renders.Demore-attempts to fetch and render data.
Preloading:
preloadRemotefunction is used to prime the cache or initiate data fetching outside of React render lifecycle, improving perceived performance on retry.
Interaction With Other Parts of the System
useRemoteData&preloadRemote(from './use-remote-data'):
These hooks/utilities handle the actual data fetching logic, caching, and preloading. This file depends on them to abstract away data retrieval details.React Suspense and Error Boundaries:
The file is a practical example of integrating React Suspense with error boundaries to handle asynchronous data fetching errors gracefully.UI Layer:
Provides the user interface for data display, loading state, error messages, and manual retry control.Possible Integration with SWR or Similar Libraries:
The pattern matches how SWR manages suspense and error boundaries, allowing easy integration with SWR's cache and mutation system.
Usage Example
import RemoteData from './manual-retry'
function App() {
return (
<div>
<h1>Remote Data Viewer</h1>
<RemoteData />
</div>
)
}
The
RemoteDatacomponent can be used anywhere in the React app to show remote data with built-in loading, error, and retry handling.
Visual Diagram
componentDiagram
component RemoteData {
+render()
}
component ErrorBoundary {
+FallbackComponent
+onReset()
}
component Suspense {
+fallback
}
component Demo {
+render()
uses useRemoteData()
}
component Fallback {
+retry button
+resetErrorBoundary()
}
RemoteData --> ErrorBoundary : wraps
ErrorBoundary --> Fallback : fallback UI on error
ErrorBoundary --> Suspense : wraps
Suspense --> Demo : wraps
Demo --> useRemoteData : fetches data
Fallback --> ErrorBoundary : resetErrorBoundary()
ErrorBoundary --> preloadRemote : onReset()
Summary
This file provides a concise but complete example of how to implement manual retry UI for Suspense-based data fetching in React:
It uses
ErrorBoundaryto catch errors and display a fallback UI.Suspense manages loading states declaratively.
The
Fallbackcomponent offers a retry button that resets the error boundary.The
onResetcallback preloads data before retrying, improving UX.The
Democomponent encapsulates data fetching via a hook with Suspense support.
This pattern is essential for resilient React applications that fetch remote data asynchronously, blending automatic and manual retry mechanisms seamlessly.
References
React Suspense: https://reactjs.org/docs/concurrent-mode-suspense.html
react-error-boundary: https://github.com/bvaughn/react-error-boundary
SWR React Hooks: https://swr.vercel.app/
Manual Retry UI and Error Boundary pattern in React
End of manual-retry.tsx documentation.