Blog>
Snippets

Suspense with Data Fetching

Demonstrate how to use React Suspense for data fetching, lazy loading components, and displaying fallback content while waiting for data.
const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Defines an asynchronous function fetchData that fetches JSON data from a specified API and returns the resulting JSON object.
const resource = fetchData();
Calls the fetchData function and stores its returned promise in the resource variable.
const LazyComponent = React.lazy(() => import('./LazyComponent'));
Uses React.lazy to dynamically import a component, which will only be loaded when it is rendered.
<React.Suspense fallback={<div>Loading...</div>}>
  <LazyComponent resource={resource} />
</React.Suspense>
Utilizes the Suspense component to wrap the LazyComponent. Suspense uses the fallback prop to display 'Loading...' until the LazyComponent is loaded and the resource data is fetched.
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.loading-text {
  font-size: 2rem;
}
Defines CSS classes for styling the loading container and text to be displayed during the lazy loading of the component.