Understanding the Basic Usage of Suspense
Basic Usage of Suspense
Suspense is a significant feature introduced in React 18, enabling elegant handling of component loading states. It is primarily used for managing asynchronously loaded components, such as dynamically imported components or those awaiting data. Suspense improves user experience by providing a fallback UI, displayed while the component or data is still loading.
Basic Structure of Suspense
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}In this example, LazyComponent is dynamically imported using the lazy function. While LazyComponent is loading, the Suspense component displays a “Loading…” placeholder.
Implementing Error Boundaries
Error boundaries are a React concept referring to components that catch and handle errors thrown by any component in their child tree. They prevent the entire application from crashing due to a single component’s error, limiting the error’s impact and displaying a fallback UI.
Implementing Error Boundaries
Error boundaries can be implemented using class or functional components, but only class components can use the static getDerivedStateFromError and componentDidCatch lifecycle methods. For functional components, libraries like react-error-boundary can be used, or future React built-in solutions may be available.
// Class-based error boundary
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log('Error caught in ErrorBoundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Using error boundary
function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}For functional components, use a library like react-error-boundary:
import ErrorBoundary from 'react-error-boundary';
function App() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<MyComponent />
</ErrorBoundary>
);
}Combining Suspense with Error Boundaries
In React 18, Suspense can also act as an error boundary to catch and handle errors during loading. When a component throws an error while loading, Suspense captures it and displays an error fallback UI.
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<Suspense
fallback={<div>Loading...</div>}
onReject={(error) => console.error('Error loading component:', error)}
>
<LazyComponent />
</Suspense>
</div>
);
}Here, the onReject prop handles loading failures, receiving an error object for logging or further error-handling logic.
Using Suspense for Data Preloading
Data Preloading
Data preloading involves fetching required data before a component renders. Traditionally, React developers use lifecycle methods or the useEffect Hook for data requests, but these approaches may not elegantly handle loading states. Suspense offers a better solution.
Example: Preloading Data with Suspense
Suppose a component needs to fetch data from a server:
import React, { Suspense } from 'react';
import { fetchData } from './dataService';
function DataComponent() {
const data = fetchData(); // Assume fetchData returns a Promise
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}To use Suspense for data preloading, modify fetchData to return a Promise and have DataComponent throw this Promise, allowing Suspense to capture it and display a fallback UI.
import React, { Suspense } from 'react';
import { fetchData } from './dataService';
async function DataComponent() {
const data = await fetchData();
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
function App() {
return (
<div>
<Suspense fallback={<div>Loading data...</div>}>
<DataComponent />
</Suspense>
</div>
);
}In this example, DataComponent is an async function that awaits fetchData’s result. If fetchData returns a Promise, DataComponent throws it, causing Suspense to render the fallback UI until the data is ready.
Using Suspense and React.lazy for Lazy Loading Components
Component lazy loading defers loading a component’s code until it is needed for rendering. This is particularly useful for large applications, as it reduces initial load time and improves performance.
Example: Lazy Loading Components with Suspense and React.lazy
React’s React.lazy function enables dynamic component imports, loading components only when required.
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading component...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}Here, LazyComponent is dynamically imported using React.lazy. Suspense displays a fallback UI until LazyComponent is fully loaded.
Combining Suspense for Data Preloading and Component Lazy Loading
In real-world applications, you may need to combine Suspense for both data preloading and component lazy loading. For example, you might want to preload data while a component loads.
import React, { lazy, Suspense } from 'react';
import { fetchData } from './dataService';
const LazyDataComponent = lazy(() => import('./LazyDataComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading component and data...</div>}>
<LazyDataComponent />
</Suspense>
</div>
);
}
async function LazyDataComponent() {
const data = await fetchData();
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}In this example, LazyDataComponent uses both React.lazy and an async function to achieve lazy loading of both the component and its data.



